在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. 分享一个裁剪图片Chrome 扩展 —— Crop Image

    1. 前言 在日常工作和设计过程中,我们常常需要对图片进行裁剪,以适配不同的使用场景.无论是社交媒体头像.网站图片优化,还是艺术设计,精确的图片裁剪都是必不可少的.然而,许多在线工具使用复杂,或者功能 ...

  2. AI与.NET技术实操系列(四):使用Semantic Kernel和DeepSeek构建AI应用

    引言 在人工智能技术飞速发展的今天,大型语言模型(Large Language Models, LLMs)已成为智能应用开发的核心驱动力.从智能客服到自动化内容生成,LLMs的应用正在深刻改变我们的工 ...

  3. Easyexcel(5-自定义列宽)

    注解 @ColumnWidth @Data public class WidthAndHeightData { @ExcelProperty("字符串标题") private St ...

  4. Windows编程----进程的当前目录

    进程的当前目录 Windows  Api中有大量的函数在调用的时候,需要传递路径.比如创建文件,创建目录,删除目录,删除文件等等.创建文件的APICreateFile做比喻,如果我们要创建的文件路径不 ...

  5. s = 0.5 * a * Math.pow(t,2),关于js动画,从一个公式说起

    s = 0.5 * a* t*t 上边这个是高中物理课本关于位移的计算公式,位移等于二分之一乘以a乘以t的平方,a是加速度,t是运动进行的时间(当然啦,初速度为0).下面我们会应用这个公式完成一个js ...

  6. 探秘Transformer系列之(13)--- FFN

    探秘Transformer系列之(13)--- FFN 目录 探秘Transformer系列之(13)--- FFN 0x00 概述 0x01 网络结构 1.1 数学表示 1.2 中间层比率 1.3 ...

  7. 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)

    FRP 是 Github 上开源的一款内网穿透工具,点击前往项目地址,该项目分为 frps 服务端和 frpc 客户端,通过在拥有公网 IP 的服务器上搭建服务端,然后在被穿透的机器上安装客户端,配置 ...

  8. 一款torrent文件格式分析工具(绿色纯天然)

    点击下载 1.主界面 2.文件分析(显示文件所在分片的位置) 3.获取指定分片所在的peers服务器列表 一只会铲史的猫

  9. Log4j2 重大漏洞,编译好的log4j-2.15.0.jar包下载

    背景 12 月 10 日凌晨,Apache 开源项目 Log4j 的远程代码执行漏洞细节被公开,由于 Log4j 的广泛使用,该漏洞一旦被攻击者利用会造成严重危害.受本次漏洞影响的版本范围为Apach ...

  10. GPT-SoVITS Windows 配置与推理笔记(自用)

    GPT-SoVITS Windows 配置与推理笔记(自用) 这是给自己留的备份,方便下次查.Windows 端配置和推理为主,代码为核心,直接干货. 环境准备 系统:Windows 10/11 Py ...