@Data
public class SomeBean {private OtherBean otherBean;
}@Data
public class OtherBean { public OtherBean() {System.out.println("OtherBean 被创建");}
}
2、XML配置bean交给Spring IoC容器管理
3、测试获取bean
public class IoCTest {@Testpublic void testXmlConfig() {ApplicationContext ctx = new ClassPathXmlApplicationContexnt("classpath:applicationContext.xml");SomeBean someBean = ctx.getBean(SomeBean.class);System.out.println(someBean);}
}
AnnotationConfigApplicationContext:该类是 ApplicationContext 接口的实现类,该对象是基于 JavaConfig 的方式来运作的 Spring 容器。
5、定义一个配置类
/**
* @Configuration
* 贴有该注解的类表示 Spring 的配置类
* 用于替代传统的 applicationContext.xml
*/
@Configuration
public class JavaConfig{/*** @Bean* 该注解贴在配置类的方法上,该方法会被 Spring 容器自动调用* 并且返回的对象交给 Spring 管理* 相当于 */@Beanpublic SomeBean(){return new SomeBean();}
}
6、测试一下
public class IoCTest {@Testpublic void testJavaConfig() {// 加载配置类,创建 Spring 容器ApplicationContext ctx = new AnnotationConfigApplicationContext(JavaConfig.class);// 从容器中取出 SomeBean 对象SomeBean someBean = ctx.getBean(SomeBean.class);System.out.println(someBean);}
}
public class JavaConfig{@Beanpublic SomeBean someBean(){return new SomeBean();}@Beanpublic OtherBean otherBean(){return new OtherBean();}
}
1、通过方法形参注入
public class JavaConfig{@Beanpublic SomeBean someBean(OtherBean otherBean){SomeBean someBean = new SomeBean();someBean.setOtherBean(otherBean);return someBean;}
}
2、通过调用方法注入
public class JavaConfig{@Beanpublic OtherBean otherBean(){return new OtherBean();}@Beanpublic SomeBean someBean() {SomeBean someBean = new SomeBean();someBean.setOtherBean(otherBean());return someBean;}
}
3、使用IoC DI注解简化配置
在配置类内部去定义方法返回 bean 对象交给 Spring 管理的方式存在一个问题,就是如果需要创建的 bean 很多的话,那么就需要定义很多的方法,会导致配置类比较累赘,使用起来不方便。
以前可以通过注解简化 XML 配置,现在同样也可以通过注解简化 JavaConfig,这里需要使用到 @ComponentScan 注解,等价于之前 XML 配置的 。
具体使用如下
两个bean类
@Component
@Data
public class SomeBean {@AutoWiredprivate OtherBean otherBean;
}@Component
public class OtherBean { public OtherBean() {System.out.println("OtherBean 被创建");}
}
JavaConfig类
@Configuration // 表示该类是 Spring 的配置类
@ComponentScan // 开启组件扫描器,默认扫描当前类所在的包,及其子包
public class JavaConfig { }
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:XML文件路径")
public class IoCTest { @Autowiredprivate SomeBean someBean;@Testpublic void test() {System.out.println(someBean);}
}
2、基于配置类的方式
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={配置类.class,.....})
public class IoCTest { @Autowiredprivate SomeBean someBean;@Testpublic void test() {System.out.println(someBean);}
}
3、Junit5的方式
@SpringJUnitConfig(配置类.class)
class IoCTest {@Autowiredprivate SomeBean someBean;@Testvoid test() {System.out.println(someBean);}
}
5、配置类的导入
1、xml方式
2、配置类方式
// 主配置类
@Configuration
@Import(OtherJavaConfig.class) // 在主配置类中关联次配置类
public class JavaConfig { ... }// 次配置类
@Configuration
public class OtherJavaConfig { ... }