@Autowired,@Bean和@Component
@Autowired
- 作用:自動按照類型注入。只要容器中有唯一的一個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
-
作用
- 此注解修飾的類就會被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容器中拿對象,如果沒有就報錯
具體可以參考此優秀博文
參考
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