Spring ----JavaConfig类代替XML配置Bean
1.使用JavaConfig实现Bean对象创建:
通过Spring ApplicationContext的另一个容器AnnotationConfigurationApplicationContext的实现类
ApplicationContext ac= new AnnotationConfigurationApplicationContext(“包名|配置类|bean工厂?”) 依赖工厂,扫描组件注入属性值。
ac.getBean();
1.@Configuration @Import("config.class")
相当于bean.xml配置类
@Configuration @ComponentScan("com.xxx.beanObject") //扫描包下所有的类,查看注解自动装配, @Import("javaconfig2.class") public class javaconfig{ @Bean public beanObject getUser(){ return beanObject;} }
@Component //直接注册User类为bean public class User { @Value("1") //给bean 属性赋初值 private int id; @Value("chen") private String name; @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }