基于Java的容器注解
@Bean标识一个用于配置和初始化一个由SpringIoc容器管理的新对象的方法,类似于XML配置文件的<bean/>
可以在Spring的@Component注解的类中使用@Bean注解任何方法(仅仅是可以)
上一点中,通常使用的是@Configuration
例子:
创建一个接口Store,和一个实现类StringStore什么都不用做只需创建,然后再创建一个StoreConfig类
StoreConfig类
package com.txr.beanannotation.javabased;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SroreConfig {
@Bean(name="store")
public Store getStringStore()
{
return (Store) new StringStore();
}
}
测试:
@Test
public void test()
{
Store store=(Store) context.getBean("store");
System.out.println(store.getClass().getName());
}
测试结果:
com.txr.beanannotation.javabased.StringStore
补充:当@Bean没有指定name时生成的Bean id标识默认为首字母小写的方法名如在这为getStringStore
测试init 与destroy
StoreConfig
package com.txr.beanannotation.javabased;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SroreConfig {
@Bean(name="store" ,initMethod="init",destroyMethod="destroy")
public Store getStringStore()
{
return (Store) new StringStore();
}
}
在StringStore中添加方法名为init与destory的方法
package com.txr.beanannotation.javabased;
public class StringStore implements Store{
public void init()
{
System.out.println("this is init");
}
public void destroy()
{
System.out.println("this is destroy");
}
}
测试结果
this is init
com.txr.beanannotation.javabased.StringStore
this is destroy