Spring之-bean注解

@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类型去查找是否容器中有注册了这样的组件,如果有多个则根据参数名来找,如果找不见就会报错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值