Spring-使用java方式的配置Spring
sjyvv 2020-01-07 13:08:08
spring
完全不使用Spring的xml配置,全权交给java来做
@Test
public void tes() {
ApplicationContext context =
new AnnotationConfigApplicationContext(Config.class);
System.out.println((User)context.getBean("get"));
}
1
2
3
4
5
6
7
2
3
4
5
6
7
//这个也会Spring容器托管,注册到容器中,因为它本来就是一个@Component
//@Configuration代表这是一个配置类,就和我们之前看的ApplicationContext.xml一样
@Configuration
@ComponentScan(value = "ann")
@Import({Config.class})
public class Config {
//注册一个bean,就相当于xml里面的bean标签
//这个方法的名字,相当于bean标签中的id属性
//这个方法的返回值,相当于bean标签中的class属性
@Bean
public User get() {
return new User();//就是返回要注入到bean的对象
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15