[Spring]8.使用javaconfig实现配置
本节作为了解。
使用了Java类代替了ApplicationContext.xml
新建一个Myconfig类
在类名上加上@Configuration,则可以作为一个配置类。

如何装配bean:
1.
在配置类中写:
@Bean
public User getUser(){
return new User();
}
方法名为bean的id。
测试方法:
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = (User) context.getBean("getUser");
System.out.println(user.getName());
注意使用了AnnotationConfigApplicationContext新建context。
- 在配置类中加上自动扫描包注解:@ComponentScan("com.wang.pojo")
- 然后在实体类上加@Component注解
则此时bean的名字变成了实体类的名字。
测试类为:
@Test
public void Test1(){
//获取spring的上下文对象
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = (User) context.getBean("user");
System.out.println(user.getName());
}

浙公网安备 33010602011771号