工具:maven、spring framework(4.2.4.RELEASE)
示例代码:https://download.csdn.net/download/u010476739/11419584
spring framwork的核心功能是依赖注入、作为对象工厂
试验条件:
maven
spring framwork 4.2.4.RELEASE
试验目的:
试验spring配置文件的加载方式,以及使用注解类代替配置文件启动容器。
Animate.java
package springconf; public interface Animate { public String show(); }Cat.java
package springconf; public class Cat implements Animate { public String show() { return "i'm Cat"; } }Dog.java
package springconf; public class Dog implements Animate { public String show() { return "i'm Dog"; } }Srv.java
package springconf; public class Srv { public Animate animate; public Animate getAnimate() { return animate; } public void setAnimate(Animate animate) { this.animate = animate; } public String show() { return animate.show(); } }AppConfig.java
package springconf; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean(name="srv") public Srv getSrv() { Srv srv = new Srv(); srv.setAnimate(new Cat()); return srv; } }App.java
package springconf; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class App { static ApplicationContext context=null; public static void main(String[] args) { //1. 寻找spring配置文件方式1 这个文件在"springconf\src\main\resources\applicationContext.xml" context = new ClassPathXmlApplicationContext("applicationContext.xml"); //2. 寻找spring配置文件方式2 效果等同上面 //context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); //3. 寻找spring配置文件方式3 使用绝对路径,一般不使用 //context = new ClassPathXmlApplicationContext("file:E:/elipsespace/springconf/target/classes/applicationContext.xml"); //4.使用注解类加载 context = new AnnotationConfigApplicationContext(AppConfig.class); System.out.println(((Srv) context.getBean("srv")).show()); } }