Spring入門(二)——DI
- 2020 年 3 月 11 日
- 筆記
1. DI
Dependency Injection,依賴注入。當對象里有屬性或對象的時候,就需要為這些屬性或對象賦值
2. 流程
這裡介紹兩種方式
- set方法
- 註解方式
2.1 set方法
Bean準備
package bean; import bean.Question; public class User { private String name; private String email; private String password; private Question question; /** * 省略了getters/setters * @author Howl */ //set方法 public void setQuestion(Question question) { this.question = question; } //構造函數 public User(String name, String email, String password) { super(); this.name = name; this.email = email; this.password = password; } }
package bean; import java.sql.Timestamp; import java.util.Date; public class Question { private int id; private Timestamp time; private String content; /** * 省略了getters/setters * @author Howl */ //構造函數 public Question(int id, Timestamp time, String content) { super(); this.id = id; this.time = time; this.content = content; } }
applictionContext.xml配置
<!--創建User對象--> <bean id="User" class="User"> <!-- 依賴注入,setting自動注入 --> <property name="Question" ref="Question"/> </bean> <!--創建Question對象--> <bean id="Question" class="Question"></bean>
獲取對象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //直接獲取 User user = ac.getBean("User");
2.2 註解方式
註解準備
package bean; import bean.Question; @Component public class User { private String name; private String email; private String password; private Question question; /** * 省略了getters/setters * @author Howl */ //set方法 @Autowired public void setQuestion(Question question) { this.question = question; } //構造函數 public User(String name, String email, String password) { super(); this.name = name; this.email = email; this.password = password; } }
獲取對象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //直接獲取 User user = ac.getBean("User");