1、实体类
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("小蠢")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
2、配置类
//这个本身是一个@Component,也会被Spring容器托管,注册在容器中
//@Configuration 代表是一个配置类,与beans.xml等价
@Configuration
@ComponentScan("com.wc.pojo")
public class WcConfig {
// 注册bean,这个方法的名字相当于id,方法的返回值相当于class
@Bean
public User getUser(){
return new User();
}
}
3、测试类
public class MyTest {
public static void main(String[] args) {
// 通过AnnotationConfig上下文获取容器,通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(WcConfig.class);
User getUser = (User) context.getBean("getUser");
System.out.println(getUser.getName());
}
}