spring bean註解使用詳解
@Bean 的用法
@Bean是一個方法級別上的註解,主要用在@Configuration註解的類裡,也可以用在@Component註解的類裡。新增的bean的id為方法名
定義bean
@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl();
}
}
這個配置就等同於之前在xml裡的配置
<beans> <bean id="transferService" class="com.acme.TransferServiceImpl"/> </beans>
bean的依賴
@bean 也可以依賴其他任意數量的bean,如果TransferService 依賴 AccountRepository,我們可以通過方法引數實現這個依賴
@Configuration
public class AppConfig {
@Bean
public TransferService transferService(AccountRepository accountRepository) {
return new TransferServiceImpl(accountRepository);
}
}
接受生命週期的回撥
public class Foo { public void init() { // initialization logic } } public class Bar { public void cleanup() { // destruction logic } } @Configuration public class AppConfig { @Bean(initMethod = "init") public Foo foo() { return new Foo(); } @Bean(destroyMethod = "cleanup") public Bar bar() { return new Bar(); } }
預設使用javaConfig配置的bean,如果存在close或者shutdown方法,則在bean銷燬時會自動執行該方法,如果你不想執行該方法,則新增@Bean(destroyMethod="")來防止出發銷燬方法
指定bean的scope
使用@Scope註解
你能夠使用@Scope註解來指定使用@Bean定義的bean
@Configuration
public class MyConfiguration {
@Bean
@Scope("prototype")
public Encryptor encryptor() {
// ...
}
}
@Scope and scoped-proxy
spring提供了scope的代理,可以設定@Scope的屬性proxyMode來指定,預設是ScopedProxyMode.NO, 你可以指定為預設是ScopedProxyMode.INTERFACES或者預設是ScopedProxyMode.TARGET_CLASS。
以下是一個demo
// an HTTP Session-scoped bean exposed as a proxy
@Bean
@SessionScope
public UserPreferences userPreferences() {
return new UserPreferences();
}
@Bean
public Service userService() {
UserService service = new SimpleUserService();
// a reference to the proxied userPreferences bean
service.setUserPreferences(userPreferences());
return service;
}
自定義bean的命名
預設情況下bean的名稱和方法名稱相同,你也可以使用name屬性來指定
@Configuration
public class AppConfig {
@Bean(name = "myFoo")
public Foo foo() {
return new Foo();
}
}
bean的別名
bean的命名支援別名,使用方法如下
@Configuration
public class AppConfig {
@Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" })
public DataSource dataSource() {
// instantiate, configure and return DataSource bean...
}
}
bean的描述
有時候提供bean的詳細資訊也是很有用的,bean的描述可以使用 @Description來提供
@Configuration
public class AppConfig {
@Bean
@Description("Provides a basic example of a bean")
public Foo foo() {
return new Foo();
}
注:
(1)、@Bean註解在返回例項的方法上,如果未通過@Bean指定bean的名稱,則預設與標註的方法名相同;
(2)、@Bean註解預設作用域為單例singleton作用域,可通過@Scope(“prototype”)設定為原型作用域;
(3)、既然@Bean的作用是註冊bean物件,那麼完全可以使用@Component、@Controller、@Service、@Ripository等註解註冊bean,當然需要配置@ComponentScan註解進行自動掃描。
bean類:
package com.test.spring.support.configuration;
//添加註冊bean的註解
@Component
public class TestBean {
public void sayHello(){
System.out.println("TestBean sayHello...");
}
public String toString(){
return "username:"+this.username+",url:"+this.url+",password:"+this.password;
}
}
配置類:
@Configuration//新增自動掃描註解,basePackages為TestBean包路徑
@ComponentScan(basePackages = "com.test.spring.support.configuration")
public class TestConfiguration {
public TestConfiguration(){
System.out.println("spring容器啟動初始化。。。");
}
//取消@Bean註解註冊bean的方式
//@Bean
//@Scope("prototype")
//public TestBean testBean() {
// return new TestBean();
//}
}
主方法測試獲取bean物件:
public class TestMain {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
//獲取bean
TestBean tb = context.getBean("testBean");
tb.sayHello();
}
}
sayHello()方法都被正常呼叫。
Spring 宣告Bean的註解:
@Component: 元件,沒有明確的角色。
@Service : 在業務邏輯層(Service層)使用。
@Repository: 再資料訪問層(Dao層)使用。
@Controller: 再展現層(MVC->Spring MVC)使用。
Spring 注入Bean的註解:
@Autowired:Spring提供的註解。
@inject:JSR-330提供的註解。
@Resource:JSP-250提供的註解。
‘@Autowired’ 和‘@Inject’他們都是通過‘AutowiredAnnotationBeanPostProcessor’ 類實現的依賴注入,二者具有可互換性。
‘@Resource’通過 ‘CommonAnnotationBeanPostProcessor’ 類實現依賴注入,即便如此他們在依賴注入時的表現還是極為相近的。
以下是他們在實現依賴注入時執行順序的概括:
@Autowired and @Inject
Matches by Type
Restricts by Qualifiers
Matches by Name
@Resource
Matches by Name
Matches by Type
Restricts by Qualifiers (ignored if match is found by name)
參考:
http://blog.csdn.net/u013474104/article/details/44352765/