Spring:XML管理Bean vs Annotation

ApplicationContext ctx = new ClassPathXmlApplicationContext("");


   需改为
 

 ApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
   


   MyConfiguration类需要加上注解@Configuration
   并在需要转成Bean的方法上加上注解@Bean,方法名则是方法名,

    如果不想用方法名做BeanID,则在注解

@Bean(value="命名BeanID")

,也可以取多个BeanID 例如

@Bean(value="{bean1,bean2}")

  若在MyConfiguration类上加上了
    @Configuration
    @ComponentScan(value = "包名")//扫描指定包名下的所有类,查看是否带有@Component注解的类并管理
    这两个注解
    则在需要被管理的类名上加上
    @Component
    还有另外三个可以达到类似目的的注解
    @Controller:被标注在Controller层
    @Service:被标注在Service层
    @Repository:被标注在Dao层
    @Component:通用型注解
    类名首字母小写就是BeanId(比如类名为Bean1,BeanId则为bean1)
   若不想要以上格式,则
   @Component(value="你想要的名称")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值