スプリングスターター(B) - DI



1. OF

依存性注入、依存性注入。オブジェクトのオブジェクトやプロパティがある場合、あなたは、これらのプロパティまたはオブジェクトに割り当てる必要があります


2.プロセス

ここで紹介する二つの方法があります

  • セット方法
  • 注釈方法

2.1セット方法

豆準備

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");


おすすめ

転載: www.cnblogs.com/Howlet/p/11980172.html