在User类中创建一个构造函数,传入参数student:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import java.io.Serializable; /**
* @author Wiener
*/
@Component
public class User implements Serializable {
private static final long serialVersionUID = 6089103683553156328L;
private Long id; private Student student; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} @Autowired // 构造函数注入参数的方式
User(Student student) {
this.student = student;
System.out.println("------ 为构造器装配Bean成功 ---------");
}
public void isStu() {
student.studentStudy();
System.out.println("------ 装配Bean成功 ---------");
}
}

其中,Student类如下:

import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component; import java.io.Serializable;
import java.util.Date; /**
* @author Wiener
*/
@Getter
@Setter
@Component
public class Student implements Serializable { private static final long serialVersionUID = -5246589941647210011L; //姓名
private String name; public Student() {
System.out.println("A default student constructor." );
}
public void studentStudy() {
System.out.println("A student is studying." );
}
}

改造Spring Boot项目启动类:

import com.east7.bean.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext; /**
* @author Wiener
*/
@SpringBootApplication
public class East7Application { public static void main(String[] args) {
ApplicationContext act = SpringApplication.run(East7Application.class, args);
User user = (User) act.getBean("user");
user.isStu();
} }

执行测试函数后,控制台打印信息如下:

A default student constructor.
------ 为构造器装配Bean成功 ---------
A student is studying.
------ 装配Bean成功 ---------

说明成员变量已经注入。此处需要注意一点,如果有两个自定义构造方法,而且都没加@Autowired注解,则会报错,因为Spring不知道你要用哪个构造方法初始化;如果只有一个构造方法加了@Autowired注解,那么就会用这个构造方法初始化;同理,如果有多个构造方法都加了@Autowired注解,那么还是会报错提示Only one constructor can have @Autowired annotation。

可以在属性中使用@Autowired 注解来省略 setter 方法。当使用@Autowired为自动连接属性传递的时候,Spring 会将这些传递过来的值或者引用自动分配给那些属性。像下面这样写在属性上并直接引用会报空指针异常:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; /**
* @author Wiener
*/
@Component
public class User { @Autowired //变量注入方式
private Student student;
private Long id = student.getId(); public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void isStu() {
id = student.getId();
student.studentStudy();
System.out.println("------ 装配Bean成功 ---------");
}
}

异常信息如下:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'user' defined in file [xxxxxx\User.class]: 
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.east7.bean.User]:
Constructor threw exception; nested exception is java.lang.NullPointerException

报错信息提示创建Bean时出错,因为实例化bean时构造方法抛出了空指针异常。如果仅仅使用函数isStu()初始化变量id, 并且把【private Long id = student.getId();】改为 【private Long id;】,则属于方法调用的时候初始化,此时,bean已经注入,不会抛异常。

其实这两种方式都可以使用,但报错的原因是加载顺序的问题,@autowired写在变量上的注入要等到类完全加载后,才会将相应的bean注入,而变量是在加载类的时候按照相应顺序加载的,所以变量的加载要早于被@autowired注解的变量,那么给变量prefix 赋值的时候所使用的a,其实还没有被注入,所以报空指针,而使用构造器则会在加载类的时候将a加载,这样在内部使用a给prefix 赋值就完全没有问题。

如果不使用构造器,那么也可以不给prefix 提前赋值,而是在系统启动后,变量prefix被使用的地方,通过a.getExcelPrefix()进行赋值,此时对a的使用是在类完全加载之后,即a被注入后,所以也是可以的。

总之,@Autowired一定要等本类构造完成后,才能从外部引用设置属性,所以@Autowired的注入时间一定会晚于构造函数的执行时间。但在初始化变量的时候就使用了还没注入的bean,所以导致了NPE。若在初始化其它变量时不使用这个要注入的bean,而是在后期调用方法的时候去初始化,是可以使用这个bean的,因为那时构造函数已经执行完毕,即已注入bean了。一言以蔽之,Java变量的初始化顺序为:静态变量或静态语句块–>实例变量或初始化语句块–>构造函数–>@Autowired 注入Bean

Spring注解之@Autowired:装配构造函数和属性的更多相关文章

  1. Spring注解之@Autowired、@Qualifier、@Resource、@Value

    前言 @Autowired.@Qualifier.@Resource.@Value四个注解都是用于注入数据的,他们的作用就和在xml配置文件中的bean标签中写一个标签的作用是一样的!本篇中特别要讲解 ...

  2. Spring注解之@Autowired

    前言 说起Spring的@Autowired注解,想必大家已经熟悉的不能再熟悉了.本文就针对此最常用的注解,梳理一下它的功能和原理,争取从源码的角度将此注解讲通,如有写的不准确的地方,欢迎各位园友拍砖 ...

  3. Spring 学习——Spring注解——Autowiring(自动装配)

    装配方式 方式一:默认 方式二:byName:根据属性名称自动装配.会查找Bean容器内部所有初始化的与属性名成相同的Bean,自动装配.(需要通过set方法注入,注入Bean的id名称需要和实体类的 ...

  4. Spring 注解实体类中非数据库字段属性

    解决办法:在属性的get方法上加上一段注解标识它是临时属性,不是数据库字段就OK @Transient public List<Reverts> getChildList() { retu ...

  5. spring 注解@Resource @Autowired区别

    1.@Autowired寻找类的时候默认是ByType,也就是通过类的类型来寻找类.不过,也可以通过借助@Qualifier("name")来指定寻找的类名 @Autowired ...

  6. Annotation(三)——Spring注解开发

    Spring框架的核心功能IoC(Inversion of Control),也就是通过Spring容器进行对象的管理,以及对象之间组合关系的映射.通常情况下我们会在xml配置文件中进行action, ...

  7. Spring注解开发系列专栏

    这个系列主要是讲Spring注解的使用,可以为后面SpringBoot的学习带来一定的帮助.我觉得从Spring直接过度到SpringBoot还是有点快,还是得需要一个演变的过程.从Spring开发, ...

  8. Spring中@Autowired注解与自动装配

    1 使用配置文件的方法来完成自动装配我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. ...

  9. Spring AOP注解通过@Autowired,@Resource,@Qualifier,@PostConstruct,@PreDestroy注入属性的配置文件详解

    本文介绍了使用Spring注解注入属性的方法.使用注解以前,注入属性通过类以及配置文件来实现.现在,注入属性可以通过引入@Autowired注解,或者@Resource,@Qualifier,@Pos ...

  10. Spring AOP注解通过@Autowired,@Resource,@Qualifier,@PostConstruct,@PreDestroy注入属性的

    本文介绍了使用spring注解注入属性的方法. 使用注解以前,注入属性通过类以及配置文件来实现.现在,注入属性可以通过引入@Autowired注解,或者@Resource,@Qualifier,@Po ...

随机推荐

  1. flex布局之flex-shrink

    当指定view为flex布局后,给子元素定义width是不起效果的. 原因:定义为flex布局元素的子元素,自动获得了flex-shrink的属性,这个属性是什么意思呢?就是告诉子元素当父元素宽度不够 ...

  2. 【多进程并发笔记】Python-Multiprocess

    目录 调用函数后,函数内的变量如何释放? python2.7怎么使用多线程加速for loop 多进程进程池,函数序列化错误的处理 Time模块计算程序运行时间 使用多进程,Start()后,如何获得 ...

  3. Selenium 报错 提示“unable to find an ant file to run”

    解决:我采用方法2解决成功 翻译:不能找到执行文件 出现问题原因:这个文件是我从电脑A拷贝到电脑B,缺少相应文件导致

  4. 基础命令:dd、tar、ln、find、逻辑符号、alisa别名、md5sun校验、lrzsz文件上传下载、wget

    目录 3.0 dd读取.转换并输出数据 3.1 压缩 (tar.zip).解压缩(tar xf.unzip) 3.2 ln软硬链接 3.2.1 软链接: 3.2.2 硬链接: 3.3 find文件查找 ...

  5. ANSYS 启动窗口过大问题解决

    方法总结(省流版):选择兼容性下更改高 DPI 设置 => 勾选高DPI 缩放代替 ,且其下对应应用程序选项 1.环境 系统环境:Windows 11 设备情况:分辨率 1920×1080:缩放 ...

  6. Python 潮流周刊#95:像人类一样使用计算机(摘要)

    本周刊由 Python猫 出品,精心筛选国内外的 250+ 信息源,为你挑选最值得分享的文章.教程.开源项目.软件工具.播客和视频.热门话题等内容.愿景:帮助所有读者精进 Python 技术,并增长职 ...

  7. 【数据结构与算法】不同路径 III:使用哈密尔顿路径算法实现

    [数据结构与算法]不同路径 III:使用哈密尔顿路径算法实现 Java 不同路径 III https://leetcode-cn.com/problems/unique-paths-iii/ 解题思路 ...

  8. Kratos 下载与安装

    前置条件 请确保已经安装好 go git protoc 然后获取 kratos 工具 go get -u github.com/go-kratos/kratos/tool/kratos 验证是否安装成 ...

  9. Python简单数据分析

    1.分析思路 以贵族价格表为例 a.使用Python连接MySQL数据库 b.从noble_right表查询贵族名称,开通价格 c.将这两组值作为XY轴绘制直方图 2.编写代码: # -*- codi ...

  10. JAVA基础之多线程三期--线程安全问题

    一.线程安全问题就是指:多个线程并发访问同一个资源而发生安全性的问题, 线程安全问题都是由全局变量及静态变量引起的. 若每个线程中对全局变量.静态变量只有读操作,而无写 操作,一般来说,这个全局变量是 ...