spring装配bean之通过java代码装配bean https://my.oschina.net/u/3711336/blog/1592958
应用场景,试图将第三方库中的组件装配到应用中,此时不能使用Component和Autowired注解的。
在此情况下需要进行显式的配置:java和xml两种
JAVA
优点:更强大,类型安全,对重构友好。
原则:不能包含任何业务逻辑,可放到单独的包中。
创建配置类并声明简单bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 这个类是一个配置类 */ @Configuration public class CDPlayerConfig { /** * bean注解告知spring这个方法会返回一个对象,并需要注册到spring应用上下文中 * 默认情况下该bean的id是sgtPeppers */ @Bean public CompactDisc sgtPeppers() { return new SgtPeppers(); } } |
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import static org.junit.Assert.assertNotNull; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * 测试开始的时候自动创建spring的应用上下文 */ @RunWith(SpringJUnit4ClassRunner.class) /** * 需要在那个地方加载配置,@ComponentScan会找到被@Component注解的类,所以应用上下文会包含CompactDisc类 */ @ContextConfiguration(classes=CDPlayerConfig.class) public class CDPlayerTest { /** * 将CompactDiscbean注入到测试代码中 */ @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull() { assertNotNull(cd); } } |
不错!不错!感觉好极了!
博客还真是个好东西!
转眼又是新一年,博主万事如意不差钱!
我有强迫症,看到好文就想顶!