定义bean 注入bean
1.bean定义:
@Component 通用组件 细分: @Controller (用于web层) @Service (用于service层) @Repository (用于dao仓库层)
2.bean取名:
@Component("test")
3.注入bean:
类型注入@Autowired
名称注入@Qualifier("test")
jdk名称或类型注入:@Resource() //如果没有指定name属性,并且按照默认的名称仍然找不到依赖对象时, @Resource注解会回退到按类型装配。但一旦指定了name属性,就只能按名称装配了。
注释:若有多个实现一个接口的类 需要用名称注入
4.bean生命周期
@PostConstruct初始化
@PreDestroy销毁
5.bean作用范围
@scope注解
@scope("prototype") 多例 (每次获取Bean的时候会有一个新的实例)
注释:默认单例
@Component
//@scope("prototype") //多例
public class Car {
private String test;
public test(){
System.out.println("Car...无参..构造器");
}
public test getTest() {
return cat;
}
public void setTest(String s) {
this.test= s;
}
//对象创建赋值之后调用
@PostConstruct
public void init(){
System.out.println("对象创建赋值之后调用");
}
//容器移除对象之时
@PreDestroy
public void destory(){
System.out.println("容器移除对象时");
}
}
spring的@Configuration和@Bean注解定义第三方bean
- @Configuration标注在类上,相当于把该类作为spring的xml配置文件中的,作用为:配置spring容器(应用上下文)
- @bean注解:用于告诉方法产生一个Bean对象,然后这个Bean对象交给Spring管理,Spring将会将这个Bean对象放在自己的IOC容器中
- 注意点:SpringIOC容器管理一个或者多个bean,这些bean都需要在@Configuration注解下进行创建
-
@Configuration public class AppConfig { //使用@bean注解,表明这个bean交个spring 进行管理 // 如果没有指定名称,默认采用 方法名 + 第一个字母小写 作为bean的名称 //initMethod = "init" 初始化加载的方法 //destroyMethod = "destroy" 销毁时加载的方法 @Bean(name = "carList",initMethod = "init",destroyMethod = "destroy") //@scope("prototype") //多例 public CarList cars(){ List<Car> carList=new ArrayList<>(); for(int i=0;i<=10;i++){ Car car = new Car(); carList.add(car); } return carList; } public void init(){ System.out.printin("初始化"): } public void destroy(){ System.out.printin("销毁"): } }
Spring的自动映射配置文件PropertySource注解:
-
@PropertySource,指定加载配置文件
- 配置文件映射到实体类
-
使用@Value映射到具体的java属性
-
@Configuration @PropertySource(value = {"classpath:config.properties"}) //resources下 public class CustomConfig { @Value("${server.host}") private String host; @Value("${server.port}") private int port; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }