@Component
public class User {
@Value("cong")
private String name;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
@Configuration//声明是一个配置类
@ComponentScan("com.cong")//用于通过注解指定spring在创建容器时要扫描的包
public class SpringConfig {
}
@Test
public void test1(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
User user = (User) context.getBean("user");
System.out.println(user.toString());
}
额外一个pojo类
public class Cat {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
'}';
}
}
配置类
@Configuration
public class Config2 {
//注册bean
//默认的bean的id是方法的名字,可以通过name或者value设置别名
//方法的返回值就是bean的class
@Bean("cat")//(name = "cat",value = "cat2")
public Cat getCat(){
Cat cat = new Cat();
cat.setName("小猫");
return cat;
}
}
引入其他配置文件
@Configuration//声明是一个配置类
@ComponentScan("com.cong")//用于通过注解指定spring在创建容器时要扫描的包
@Import(Config2.class)//导入其它配置类
public class SpringConfig {
}
测试
@Test
public void test1(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
User user = (User) context.getBean("user");
System.out.println(user.toString());
Cat cat = (Cat) context.getBean("cat");
System.out.println(cat.toString());
}
原文:https://www.cnblogs.com/ccoonngg/p/12026761.html