@Autowired,@Bean和@Component


@Autowired,@Bean和@Component

@Autowired

image-20200329120051842

  • 作用:自动按照类型注入。只要容器中有唯一的一个bean对象要和注入的变量类型匹配,就可以注入成功
  • 出现位置:
    • 变量上
    • 方法上
  • 注意:
    • 如果ioc容器中有多个类型匹配时:会先找数据类型,然后根据变量名称匹配。
    • 如果ioc容器中没有任何类型bean和要注入的数据类型匹配(或类型匹配但变量名称不匹配),则报错
作用在变量上
@Service
public class AccountServiceImpl implements IAccountService {
    
    @Autowired//自动按照类型注入
    private IAccountDao accountdao;
    
    public void saveAccount() {
        //不需要再new了 大大降低了程序间的耦合
        //此处不懂可以去研究SpringIOC的原理
        accountdao.saveAccount();
    }
}
作用在方法上
  • 该方法如果有参数,会使用@autowired的方式在容器中查找是否有该参数
@Service
public class AccountServiceImpl implements IAccountService {
    
    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }
}
  • 注意
    • spring容器会在类加载后自动注入这个方法的参数,并执行一遍方法。
    • 这就像static{}块语句会初始化执行,但顺序不一样。static{}更快

@Component

image-20200327135255853

  • 作用

    • 此注解修饰的类就会被Spring扫描到并注入到Spring的bean容器中
  • 出现位置

    • 接口、类、枚举、注解
  • 注意

    • @Controller 注解的bean会被spring-mvc框架所使用。
    • @Repository 会被作为持久层操作(数据库)的bean来使用
    • @Component是自定义能力最好的注解
  • 细节

    • @Component就是跟<bean>一样,可以托管到Spring容器进行管理。
    • @Service, @Controller , @Repository = {@Component + 一些特定的功能}。这个就意味着这些注解在部分功能上是一样的。
    • 此4个注解功能一样,仅名字不同,但能够区分层次,代码之间的调用也清晰明朗,便于项目的管理

@Bean

  • 作用
    • @Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名
  • 出现的位置
    • 方法、注解
定义Bean

下面是@Configuration里的一个例子

@Configuration
public class AppConfig {

    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }

}

这个配置就等同于在xml里的配置

<beans>
    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
</beans>

总结

  • @Component就是把这个类注册进Spring容器中管理

  • 如果类没注册进Spring容器中,那么@Bean和@Autowired统统都会失效

  • @Bean就是这个方法返回的对象,放入Spring容器中进行管理

  • @Autowired就是从Spring容器中拿对象,如果没有就报错

具体可以参考此优秀博文

spring4.0之二:@Configuration的使用

spring @Bean注解的使用

参考

http://bcxw.net/article/53.html

https://www.jianshu.com/p/3fbfbb843b63

http://www.tomaszezula.com/2014/02/09/spring-series-part-5-component-vs-bean/

https://www.cnblogs.com/duanxz/p/7493276.html

https://blog.csdn.net/fansili/article/details/78740877

https://blog.csdn.net/qq346859029/article/details/82356103


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM