spring依赖注入(1)-自动注入

在需要添加自动注入的类加入注解
@Component
在类中,如果需要注入别的类,这个时候声明别的类,然后添加@AutoWried
具体例子

@Component
public class CDPlayer implements MediaPlayer {
    @AutoWried
    private CompactDisc cd;

   

    @Override
    public void play() {
        cd.play();
    }
}

系统在扫描时,发现@Component注解会将CDPlayer放入应用上下文,而在扫描到@AutoWried时,会将应用上下文中的ComPactDisc注入到里面

spring当中配置分为:javaConfig和xml
而在javaConfig


@Configuration
@ComponentScan
public class CDPlayerConfig {
}

此处使用@CompontScan注解,会去寻找当前CDPlayer所在位置的包里面的各个类,并进行注解扫描,当然CDPlayerConfig也被扫描到了,因为它使用了@Configuration注解。。当然@CompontScan也可以设置扫描具体的包,可以注解里面添加配置(具体遇到再说)

xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.husky.spring"/>

</beans>

具体测试的时候可以使用这个注解
@ContextConfiguration(classes=CDPlayerConfig.class)
或者*@ContextConfiguration(locations = “classpath:spring/soundsystem.xml”)*

/**
 * @author husky
 * @date 2018/10/17 16:31
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerJavaConfigTest {
    @Rule
    public final  StandardOutputStreamLog log = new StandardOutputStreamLog();

    @Autowired
    private MediaPlayer player;

    @Autowired
    private CompactDisc cd;

    @Test
    public void cdShouldNotBeNull(){
        assertNotNull(cd);
    }

    @Test
    public void play(){
        player.play();
        assertEquals("Playing Sgt . Pepper's Lonely Hearts Club Band by The Beatles\n",log.getLog());
    }
}

具体autoconfig在github

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值