Spring注解之@Autowired:Setter 方法上使用@Autowired注解
可以在 JavaBean中的 setter 方法中使用 @Autowired 注解。当 Spring遇到一个在 setter 方法中使用的 @Autowired 注解时,它会在方法中按照类型自动装配参数值。创建测试类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 Student getStudent() {
return student;
}
@Autowired
public void setStudent(Student student) {
this.student = student;
}
public void isStu() {
student.studentStudy();
System.out.println("------ 装配Bean成功 ---------");
}
}
下面创建依赖的类文件 Student.java,切莫忘记在类文件上添加注解 @Component:
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启动类,通过Spring容器拿到Bean实例user:
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.
A student is studying.
------ 装配Bean成功 ---------
说明student属性被装配成功。如果setStudent方法不加注解,程序运行时,会抛出如下异常:
Exception in thread "main" java.lang.NullPointerException
at com.east7.bean.User.isStu(User.java:28)
at com.east7.East7Application.main(East7Application.java:25)
读后有收获,小礼物走一走,请作者喝咖啡。

作者:楼兰胡杨
本文版权归作者和博客园共有,欢迎转载,但请注明原文链接,并保留此段声明,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
2018-07-11 java怎么实现统计一个字符串中字符出现的次数