spring注解版(2)

一.bean的生命周期(bean的创建-初始化-销毁)

  • 单实例:在容器启动时创建对象,容器关闭的时候销毁
  • 多实例:在每次获取时创建对象,容器不会管理这个bean,容器不会调用销毁方法
    (1).指定初始化和销毁方法
    ①.通过@Bean注解指定init-method和destroy-method
    第一步:创建Bean,在Bean中定义初始化和销毁方法
package com.atguigu.bean;
import org.springframework.beans.factory.FactoryBean;
public class ColorFactoryBean implements FactoryBean<color>{
//返回一个color对象,这个对象会添加到容器中
public color getObject() throws Exception {
  // TODO Auto-generated method stub
  System.out.println("getObject()...");
  return new color();
 }
 //对象类型
 public Class<?> getObjectType() {
  return color.class;
 }
//是否单例
// true:是:第一次获取时调用getObject()方法获取bean,在容器中保存一份
// false:否:每次获取都会调用getObject()方法获取一个新的bean
public boolean isSingleton() {
  return true;
 }
}

第二步:将Bean加入Ioc容器中,并指定对应的初始化销毁方法

配置类中

@Bean(initMethod="init",destroyMethod="destory")
public Car car() {
 return new Car();
}

②.通过Bean实现InitializingBean(初始化逻辑),DisposableBean(销毁逻辑)
第一步:创建bean,实现InitializingBean,DisposableBean接口

package com.atguigu.bean;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class cat implements InitializingBean,DisposableBean {
public cat() {
 System.out.println("cat constructor...");
}
public void destroy() throws Exception {
  // TODO Auto-generated method stub
  System.out.println("cat constructor...");
 }
 //在Properties设置之后
 public void afterPropertiesSet() throws Exception {
  // TODO Auto-generated method stub
  System.out.println("cat...afterPropertiesSet...");
 }
}

第二步:将bean加入ioc容器

@ComponentScan("com.atguigu.bean")

③.可以使用JSR250

  • @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
  • @PreDestroy:在容器销毁bean之前通知我们进行清理工作
    使用:创建bean
    第一步:创建Bean,在Bean中定义并加入注解初始化(@PostConstruct)和销毁方法(@PreDestroy),
package com.atguigu.bean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.stereotype.Component;
@Component
public class dog {
public dog() {
 System.out.println("dog constructor...");
}
@PostConstruct
public void init() {
 System.out.println("dog...PostConstruct...");
}
@PreDestroy
public void detory() {
 System.out.println("dog...@PreDestroy...");
}
}

第二步:将bean加入ioc容器

@ComponentScan("com.atguigu.bean")

④.BeanPostProcessor:bean的后置处理器;
在每一个bean初始化前后进行一些处理工作:

  • postProcessBeforeInitialization:在初始化之前工作
  • postProcessAfterInitialization:在初始化之后工作
    使用
    第一步:实现BeanPostProcessor
package com.atguigu.bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
//Bean初始化之前工作
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
 System.out.println("postProcessBeforeInitialization... "+bean+" ...");
  return bean;
 }
 //Bean初始化之后工作
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  System.out.println("postProcessAfterInitialization... "+bean+" ...");
  return bean;
 }

}

第二步:将BeanPostProcessor加入ioc容器

@ComponentScan("com.atguigu.bean")

底层原理
遍历得到容器中所有的BeanPostProcessor;挨个执行beforeInitialization,
一但返回null,跳出for循环,不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization
BeanPostProcessor原理
populateBean(beanName, mbd, instanceWrapper);给bean进行属性赋值
initializeBean
{
applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化
applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
Spring底层对 BeanPostProcessor 的使用;
bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async,xxx BeanPostProcessor;

二.属性赋值

使用@Value赋值
(1).基本数值

@Value("张三")
private String name;

(2).可以写SpEL;#{}

private String name;
 @Value("#{20-2}")

(3).可以写${};取出配置文件中的值(在运行环境变量里面的值)
第一步:创建person.properties配置文件

person.nickName=\u5C0F\u5F20\u4E09

第二步:在person类中nickName属性上加上@Value("${person.nickName}")

@Value("${person.nickName}")
private String nickName;

第三步:配置类

package com.atguigu.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import com.atguigu.bean.person;
//使用@PropertySource读取外部配置文件中的K/v保存到运行的环境变量中
@PropertySource(value = { "classpath:/person.properties" })
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public person p() {
 return new person();
}
}

测试类

@Test
public void test01() {
AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
 person p=(person)applicationContext.getBean(person.class);
    System.out.println(p);
}

结果
person [name=张三, age=18, nickName=小张三]

如果用@PropertySource或其他方式将 person.properties保存进运行的环境中,则还可以通过下面方式获取配置文件中person.nickName的值

   ConfigurableEnvironment environment= applicationContext.getEnvironment();
   String property=environment.getProperty("person.nickName");
   System.out.println(property);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值