demo
实体Entity:
@Component
public class User {
@Value("Jack")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置类Configuration:
@Configuration
@ComponentScan("com.t c.entity")
@Import(TConfig.class)
public class MyConfig {
@Bean
User getUser(){
return new User();
}
}
测试类:
注意:使用ApplicationContext的实现类AnnotationConfigApplicationContext来获取IOC容器中的配置类所装配的Bean
public class TestMain {
public static void main(String[] args){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
User user = (User)applicationContext.getBean("getUser");
Pet pet = (Pet)applicationContext.getBean("getPet");
System.out.println(pet.getPetName());
}
}
1、@Configuration
1.1 描述
(1)在Spring3.0后以一个独立的项目并入到Spring中
(2)一个用于装配Bean的的Spring配置类,和xml作用相同
(3)相当于<beans></beans>
2、@Import
(1)引入其他的配置类
(2)相当于<import resource="beans3.xml"></import>
3、@ComponentScan
(1)指定扫描类的路径
(2)相当于<context:component-scan base-package="dao"/>