@Bean注解
@bean注解是Spring中的一个重要注解,主要是用在方法上,将该方法发返回值注册成一个Bean,并加入到Spring中进行管理。
使用方法
@Configuration
public class EntityServiceImpl {
@Bean
public Entity myEntity()
{
Entity entity=new Entity();
entity.setI(1);
return entity;;
}
}
从上面代码中可以看出,使用@Bean注解,还需要在对应的方法所在的类上增加@Configuration,先把对应的类注册进IOC容器中,然后才能通过@Bean注解将方法的返回值注册为bean,并且在未定义name参数时,默认以方法名为beanName注册进容器中。所有可以用以下方法调用:
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(EntityServiceImpl.class);
Entity e= (Entity) ctx.getBean("myEntity");
System.out.println(e);
}
output:
Entity{i=1, j=0}
注解属性解析
@bean有四个参数,分别是value,name,initMethod,destroyMethod
- value:用来修改被注册bean在IOC容器中的id属性
- name:用来修改被注册bean在IOC容器中的id属性
- initMethod:用来指定初始化方法(相当于xml文件中的init-method)
- destoryMethod:用来之帝国销毁方法 (相当于xml文件中的destory-method)
其中value和name用法相同,并且要注意这两个属性不能并存
修饰带参方法
当@Bean修饰带参数的方法时,会从Spring容器中根据类型注入(若有多个类型的的话则根据方法名按名称注入,没有找到就会报错)
例如
@Bean
public HelloService hello(HelloProperties helloproperties){
return new HelloService (helloproperties);
}
这时候就会先根据HelloProperties类型去查找是否容器中有注册了这样的组件,如果有多个则根据参数名来找,如果找不见就会报错