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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM