有不懂的可以参考之前的文章!

https://www.cnblogs.com/Mrchengs/p/10109053.html

1.Bean的生命周期

    创建---初始化---销毁
 
容器管理bean的生命周期:
我们可以自定义初始化和销毁的方法
 
构造器: 
    1.单实例:在容器创建好之后创建实例
    2.多实例:在每次获取的时候创建对象
 
初始化:
    对象创建好,并赋值好,进行初始化
销毁:
    单实例:容器关闭的时候
    多实例:容器不会管理这个bean,在容器关闭的时候不会调用销毁的方法
1.指定初始化和销毁的方法:通过@Bean的注解
    相当于:init-method,destroy-method
public class Chirld {

     public Chirld() {
System.out.println("创建Child实例....");
}
public void init(){
System.out.println("初始化方法.....");
}
public void destroy(){
System.out.println("销毁方法....");
}
}
@Configuration
public class TheLifeOfInitAnfDestroy {
@Bean(initMethod="init",destroyMethod="destroy")
public Chirld car(){
return new Chirld();
}
}
     @Test
public void test4(){
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(TheLifeOfInitAnfDestroy.class); System.out.println("容器创建完成");
//关闭
app.close();
}
创建Child实例....
初始化方法.....
容器创建完成
十一月 , :: 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@512ddf17: startup date [Fri Nov :: CST ]; root of context hierarchy
销毁方法....

在容器关闭的时候进行销毁

2.接口方法

通过Bean实现InitializingBean自定义初始化逻辑
                       DisposableBean自定义销毁容器
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
public interface DisposableBean {
void destroy() throws Exception;
}
@Component
public class Chirld2 implements InitializingBean,DisposableBean { public Chirld2() {
System.out.println("创建Child2实例....");
}
public void afterPropertiesSet() throws Exception {
System.out.println("init....."); }
public void destroy() throws Exception {
System.out.println("destroy....");
}
}
@Configuration
@ComponentScan("coom.MrChengs.bean")
public class TheLifeOfInitAnfDestroy { }
@Test
public void test4(){
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(TheLifeOfInitAnfDestroy.class); System.out.println("容器创建完成");
//关闭
app.close();
}
创建Child2实例....
init.....
容器创建完成
十一月 , :: 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@512ddf17:
   startup date [Fri Nov :: CST ]; root of context hierarchy
destroy....
3.可以使用JSR250
    @PostConStruct:在bean创建完成并且属性赋值完成,来执行初始化
    @PreDestroy:在容器销毁bean之前通知我们进行清理

//代码.....

4.BeanPostProcessor接口:bean的后置处理器

在bean初始化之后进行一些处理工作
  postProcessBeforeInitialization:在初始化之前工作
 
  postProcessAfterInitialization:  在初始化之后工作
@Component
public class MyBeanPostProcessor implements BeanPostProcessor{
     //bean:刚刚创建的实例
     //beanName:bean的名字
     public Object postProcessBeforeInitialization(Object bean,  String beanName) throws BeansException {
           System.out.println("post init....."); 
           return bean;
     }
     public Object postProcessAfterInitialization(Object bean,  String beanName) throws BeansException {
           System.out.println("aftet init ....");
           return bean;
     }
}
@Configuration
@ComponentScan("coom.MrChengs.bean")
public class TheLifeOfInitAnfDestroy {
}
     @Test
public void test4(){
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(TheLifeOfInitAnfDestroy.class);
System.out.println("容器创建完成");
//关闭
app.close();
}
post init.....
aftet init ....
post init.....
aftet init ....
post init.....
aftet init ....
创建Child2实例....
post init.....
init.....
aftet init ....
容器创建完成
十一月 , :: 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@512ddf17: startup date [Fri Nov :: CST ]; root of context hierarchy
destroy....
底层对BeanPostProcessor的使用:
bean赋值,注入其他组建,@Autowire,生命周期注解功能。。。。。

 2.属性赋值:

@Value("")
1.基本数值
2.可以写Spel : #{}
3.可以写 ${ } ,取出配置文件中的只

person.properties

person.school=MrChengs
public class Person {

     @Value("MrChengs")
private String name;
@Value("#{20-12}")
private int age;
@Value("${person.school}")
private String school;
...
}
@Configuration
//引入资源
@PropertySource(value={"classpath:/person.properties"})
public class ValueConfig {
@Bean
public Person person(){
return new Person();
}
}
@Test
public void test5(){
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(ValueConfig.class); String [] names = app.getBeanDefinitionNames();
for(String name : names){
System.out.println(name);
}
Person person = app.getBean(Person.class);
System.out.println(person); }
valueConfig
person
Person [name=MrChengs, age=8, school=MrChengs]
@PropertySource(value={"classpath:/person.properties"})用于加载配置文件
public @interface PropertySource {

     String name() default "";

     String[] value();

     boolean ignoreResourceNotFound() default false;

     String encoding() default "";

     Class<? extends PropertySourceFactory> factory() default  PropertySourceFactory.class;
}

自动装配:

利用依赖注入(DI)完成对IOC容器中各个组件的依赖关系。
前提自动注入的需要提前在容器中

@Autowired

1.默认优先按照类型进行容器组件中查找
2.当容器中有多个相同类型的组件,再将属性的名作为组件的id去容器中查找
applicationContext.getBean("customerDao")...

     @Autowired
private CustomerDao customerDao;
默认按照方法名去id中查找
3.  @Qualifier
指定需要装配的组件id
 @Qualifier("customerDao")
@Autowired
private CustomerDao customerDao2;
4.默认一定将属性赋值好
5.如果没有的情况下组件默认是null
    不是必须的,此时容器中没有所需要装配的bean也不会报错
     @Qualifier("customerDao")
@Autowired(required=false)
private CustomerDao customerDao2;

6.@Primary:让spring进行装配的时候,默认使用首选的bean

     @Autowired(required=false)
private CustomerDao customerDao; @Primary
@Bean("customerDao2")
public CustomerDao customer(){
...
}
@Repository
public class CustomerDao {
}
@Service
public class CustomerService {
@Autowired
private CustomerDao customerDao; public void print(){
System.out.println("---->"+customerDao);
}
}
@Configuration
@ComponentScan({"coom.MrChengs.config.service","coom.MrChengs.config.dao"})
public class AutowiredConfig {
@Bean("customerDao2")
public CustomerDao customer(){
return new CustomerDao("customer2");
} }
     @Test
public void test6(){
AnnotationConfigApplicationContext app = new
    AnnotationConfigApplicationContext(coom.MrChengs.config.AutowiredConfig.class); String [] names = app.getBeanDefinitionNames();
for(String name : names){
System.out.println(name);
}
CustomerService cus = app.getBean(CustomerService.class);
cus.print();
//System.out.println(cus);
}
autowiredConfig
customerService 此时容器中有两个相同类型的bean
customerDao
customerDao2 此时注入的类型是:
---->CustomerDao [name=null]
spring还支持@Resource和@Inject   java规范注解
@Resource
可以实现和@Autowire一样的功能 实现,默认是按照组件的名称进行装配
     @Resource
private CustomerDao customerDao;

可以修改器默认装配的名称

     @Resource(name="customerDao2")
private CustomerDao customerDao;

不可以支持@Primary功能和request=false的功能

@Inject
需要导入下面的依赖
<!-- https://mvnrepository.com/artifact/javax.inject/javax.inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
     @Inject
private CustomerDao customerDao;
其实先功能和@Autowire功能一样
其本身没有属性,没有require=false这个属性
支持@Primary

@Autowire

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD,  
ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {

可以标注的位置有构造器,方法,属性

方法上

@Component
public class Person {
...
}
@Component
public class Students {
...
@Autowired
public void setPerson(Person person) {
this.person = person;
}
..
}
     AnnotationConfigApplicationContext app = new  
AnnotationConfigApplicationContext(coom.MrChengs.config.AutowiredConfig.class); Students s = app.getBean(Students.class); System.out.println(s);
Person p = app.getBean(Person.class);
System.out.println(p);
Students [person=Person [name=MrChengs, age=,  school=${person.school}], name=null]
Person [name=MrChengs, age=, school=${person.school}]
构造器:
     @Autowired
public Students(Person person, String name) {
super();
this.person = person;
this.name = name;
System.out.println("Students.....");
}
1.标注在方法位置上,@Bean+方法参数,参数从容器中获取
2.标注在构造器上:如果组件只有一个构造函数,可以省略
3.放在参数位置

3spring:生命周期,属性赋值,自动装配的更多相关文章

  1. Spring笔记(2) - 生命周期/属性赋值/自动装配及部分源码解析

    一.生命周期 @Bean自定义初始化和销毁方法 //====xml方式: init-method和destroy-method==== <bean id="person" c ...

  2. Spring Bean 注入 1 - 构造方法注入,属性注入,自动装配

    1.代码结构图 xxx 2.bean代码 package com.xxx.bean; /** * Created with IntelliJ IDEA. * User: zhenwei.liu * D ...

  3. 从EFCore上下文的使用到深入剖析DI的生命周期最后实现自动属性注入

    故事背景 最近在把自己的一个老项目从Framework迁移到.Net Core 3.0,数据访问这块选择的是EFCore+Mysql.使用EF的话不可避免要和DbContext打交道,在Core中的常 ...

  4. Spring 框架基础(02):Bean的生命周期,作用域,装配总结

    本文源码:GitHub·点这里 || GitEE·点这里 一.装配方式 Bean的概念:Spring框架管理的应用程序中,由Spring容器负责创建,装配,设置属性,进而管理整个生命周期的对象,称为B ...

  5. Spring - bean的autowire属性(自动装配)

    当我们要往一个bean的某个属性里注入另外一个bean,我们会使用<property> + <ref/>标签的形式.但是对于大型项目,假设有一个bean A被多个bean引用注 ...

  6. spring4笔记----spring生命周期属性

    init-method : 指定bean的初始化方法-spring容器会在bean的依赖关系注入完成后调用该方法 destroy-method :指定bean销毁之前的方法-spring容器将会在销毁 ...

  7. 浅尝Spring注解开发_自定义注册组件、属性赋值、自动装配

    Spring注解开发 浅尝Spring注解开发,基于Spring 4.3.12 包含自定义扫描组件.自定义导入组件.手动注册组件.自动注入方法和参数.使用Spring容器底层组件等 配置 @Confi ...

  8. bean的autowire属性及其生命周期

    一:sutowire属性 1.no:默认值,禁用自动装配: 2.byName:根据属性名称自动装配: 3.byType:根据属性类型自动装配: 4.constructor:通过构造方法自动装配,不推荐 ...

  9. [原创]java WEB学习笔记99:Spring学习---Spring Bean配置:自动装配,配置bean之间的关系(继承/依赖),bean的作用域(singleton,prototype,web环境作用域),使用外部属性文件

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

随机推荐

  1. IE9 和IE10 兼容性判断及效果

    仅IE9可识别 .d1{ width:100px; height:100px; background:blue; } IE9及一下使用<!--[if IE 8]><![endif]- ...

  2. 安装mysql Install/Remove of the Service Denied!错误的解决办法

    在window 的cmd下安装mysql 在mysql的bin目录下面执行: mysqld --install 报错: 信息如下: Install/Remove of the Service Deni ...

  3. Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

    环境 Android Studio 3.0 升级&导入项目 错误 Error:java.util.concurrent.ExecutionException: com.android.tool ...

  4. easypoi导出单个sheet和多个sheet

    今天有时间研究了一下easypoi,感觉使用了easypoi导出excel方便了很多,不用写很多复杂的反射,只需要使用注解和一些工具类就可以实现常用的excel的导出,接下来介绍一下easypoi如何 ...

  5. POJ 1185 炮兵阵地 经典的 状态压缩dp

    炮兵阵地 Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 16619   Accepted: 6325 Description ...

  6. 读EntityFramework.DynamicFilters源码_心得_单元测试03

    上个星期我们只是显示了一个示例,怎么在EF的框架内,注入我们拓展的动态过滤器 第一步:安装EntityFramework.DynamicFilters 第二步:重写OnModelCreating方法 ...

  7. child_process

    child_process const { spawn } = require('child_process'); const ls = spawn('ls', ['-lh', '/usr']); l ...

  8. java 从Excel 输出和输入

    本文实现了使用java 从数据库中获得对象,并存入集合中, 然后输出到Excel,并设置样式 package com.webwork; import java.io.File; import java ...

  9. centos install redis

    1. 下载 [logan@localhost java]$ wget http://download.redis.io/releases/redis-3.2.8.tar.gz2. 解压    [log ...

  10. jquery not() 方法

    1.not(expression) 根据表达式参数的值,从包装集里删除元素 example : $('img[alt]').not('[alt*=joy]') 返回包含属性alt的img元素,但img ...