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="你想要的名称")