Spring學習 -- Bean的依賴注入方式
阿新 • • 發佈:2021-01-21
UserDao怎樣注入到UserService內部呢?
1.設值注入(主要)
1)編寫User類
package com.contactDemo.entity; public class User { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "age=" + age + ", name='" + name + '\'' + '}'; } }
2)設定注入
<bean id="User" class="com.contactDemo.entity.User">
<property name="age" value="13" />
<property name="name" value="張三" />
</bean>
3)執行測試
package com.contactDemo; import com.contactDemo.entity.User; import org.springframework.context.support.ClassPathXmlApplicationContext; public class contactDemo { public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User) applicationContext.getBean("User"); System.out.println(user); } }
4)結果展示
2.構造注入
1)User實體類(實現有參構造方法)
package com.contactDemo.entity; public class User { private int age; private String name; public User(){} // 加入有引數構造 public User(int age, String name){ this.age = age; this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "age=" + age + ", name='" + name + '\'' + '}'; } }
2)構造注入
<!-- 構造注入 -->
<bean id="User" class="com.contactDemo.entity.User">
<constructor-arg name="age" value="13"/>
<constructor-arg name="name" value="張三"/>
</bean>
3)執行測試
package com.contactDemo;
import com.contactDemo.entity.User;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class contactDemo {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) applicationContext.getBean("User");
System.out.println(user);
}
}
4)執行結果
3.介面注入
主要應用於資源來自於非自身系統,而是來自外界,例如資料庫連線資源可以在tomcat下配置,然後通過JNDI去獲取這時候可以採用介面注入來獲取它。
配置tomcat資料來源-程式碼(context.xml):
<Context>
<Resource name="jdbc/ssm"
auth="Container"
type="javax.sql.DateSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysel://localhost:3306/ssm?zeroDateTimeBehavior=convertToNull"
username="root"
password:"123"
/>
</Context>
// 通過JNDI獲取資料庫連線資源-程式碼:
<bean id="dateSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/ssm</value>
</property>
</bean>
這樣就可以在Spring的IoC容器中獲得Tomcat所管理的資料庫連線池了。