Spring框架簡介⑤

Milky-way發表於2018-08-07

七 依賴注入

1 常量注入

User類

package com.rl.spring.model;

public class User {
	
	private Integer userId;
	
	private String username;
	
	private String password;
	
	public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User() {
		System.out.println("user被建立");
	}

	public void init(){
		System.out.println("我出來了");
	}
	public void destroy(){
		System.out.println("20年後又是一條好漢");
	}
	
	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

    @Override
    public String toString() {
        return "User [userId=" + userId + ", username=" + username + ", password=" + password + "]";
    }
}

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

	<bean id="user" class="com.rl.spring.model.User">
	   <property name="userId" value="1"></property>
	   <property name="username" value="lijialin"></property>
	   <property name="password" value="123"></property>
	</bean>
	
</beans>

測試類:

package com.rl.spring.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rl.spring.model.User;

public class TestSpring {

	@Test
	public void test() {
		ApplicationContext ctx =
				new ClassPathXmlApplicationContext("ApplicationContext.xml");
		User user = (User) ctx.getBean("user");
		System.out.println(user);
	}
}

測試輸出:

User [userId=1, username=lijialin, password=123]

 

2 構造器注入

注入常量

User類: 在該類中新增有參構造器, 同時需要新增無參構造器

package com.rl.spring.model;

public class User {
	
	private Integer userId;
	
	private String username;
	
	private String password;
	
	public User() {
    }
	
	public User(Integer userId, String username, String password) {
        super();
        this.userId = userId;
        this.username = username;
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

	public void init(){
		System.out.println("我出來了");
	}
	public void destroy(){
		System.out.println("20年後又是一條好漢");
	}
	
	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

    @Override
    public String toString() {
        return "User [userId=" + userId + ", username=" + username + ", password=" + password + "]";
    }
}

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

	<bean id="user" class="com.rl.spring.model.User">
	<!-- 
	   index是指構造方法中的引數的索引, 從0開始
	   value是值
	 -->
	   <constructor-arg index="0" value="1"/>
	   <constructor-arg index="1" value="lijialin"/>
	   <constructor-arg index="2" value="123"/>
	</bean>
</beans>

測試輸出:

User [userId=1, username=lijialin, password=123]

 

注入變數

UserServiceImpl類:

需要在UserServiceImpl類中提供有參和無參的構造方法

package com.rl.spring.service.impl;

import com.rl.spring.dao.UserDao;
import com.rl.spring.service.UserService;

public class UserServiceImpl implements UserService {

	private UserDao userDao;
	
	public UserServiceImpl() {
    }
	
	public UserServiceImpl(UserDao userDao) {
        super();
        this.userDao = userDao;
    }

    @Override
	public void save() {
		userDao.save();
	}

}

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">


    <bean id="userDao" class="com.rl.spring.dao.impl.UserDaoImpl"></bean>
    
    <!-- 
        index: 引數只有一個UserDao 索引為0
        type: UserDao的包路徑(需要是介面的包路徑)
        ref: 引入的userDao的bean的id
     -->
    <bean id="userService" class="com.rl.spring.service.impl.UserServiceImpl">
        <constructor-arg index="0" type="com.rl.spring.dao.UserDao" ref="userDao" />
    </bean>
</beans>

測試程式碼:

package com.rl.spring.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rl.spring.service.UserService;

public class TestSpring {

	@Test
	public void test() {
		ApplicationContext ctx =
				new ClassPathXmlApplicationContext("ApplicationContext2.xml");
		
		UserService userService = (UserService) ctx.getBean("userService");
		
		userService.save();
	}
}

輸出:

user被儲存了

 

3 外部bean注入(最常用的注入方式)

外部bean的注入方式必須在UserServiceImpl類中提供set...方法

UserServiceImpl類:

package com.rl.spring.service.impl;

import com.rl.spring.dao.UserDao;
import com.rl.spring.service.UserService;

public class UserServiceImpl implements UserService {

	private UserDao userDao;
	
	public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
	
    @Override
	public void save() {
		userDao.save();
	}

}

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <bean id="userDao" class="com.rl.spring.dao.impl.UserDaoImpl"></bean>

    <!-- 
        name: UserServiceImpl類中的userDao屬性
        ref: 引入上面userDao這個bean
     -->
    <bean id="userService" class="com.rl.spring.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>

</beans>

測試程式碼跟輸出結果同上

 

4 內部bean注入(較少使用)

UserServiceImpl類跟同上需要set方法

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <!-- 內部bean的注入形式
                缺點是無法再給其他bean引用
     -->
    <bean id="userService" class="com.rl.spring.service.impl.UserServiceImpl">
        <property name="userDao">
            <bean class="com.rl.spring.dao.impl.UserDaoImpl"></bean>
        </property>
    </bean>
    
</beans>

測試程式碼和輸出同上

 

5 集合注入

集合注入能夠注入 set list map property

建立一個新的類CollectionInjection

package com.rl.spring.model;

import java.util.Set;

public class CollectionInjection {

    private Set<String> set;

    public Set<String> getSet() {
        return set;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }
}

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <bean id="ci" class="com.rl.spring.model.CollectionInjection">
    <!-- 屬性set -->
        <property name="set">
            <set>
            <!-- 給集合賦值 -->
                <value>football</value>
                <value>basketball</value>
            </set>
        </property>
    </bean>
    
</beans>

測試程式碼:

package com.rl.spring.test;

import java.util.Set;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rl.spring.model.CollectionInjection;
import com.rl.spring.service.UserService;

public class TestSpring {

	@Test
	public void test() {
		ApplicationContext ctx =
				new ClassPathXmlApplicationContext("ApplicationContext5.xml");
		CollectionInjection ci = (CollectionInjection) ctx.getBean("ci");
		Set<String> set = ci.getSet();
		System.out.println(set);
	}
}

輸出結果:

[football, basketball]

list集合跟set集合相同

map集合跟list跟set集合的用法類似, 區別在於配置檔案有些許不同

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <bean id="ci" class="com.rl.spring.model.CollectionInjection">
    <!-- 屬性set -->
        <property name="set">
            <set>
            <!-- 給集合賦值 -->
                <value>football</value>
                <value>basketball</value>
            </set>
        </property>
        
        <property name="map">
            <map>
                <entry key="key1" value="value1"></entry>
                <entry key="key2" value="value2"></entry>
            </map>
        </property>
    </bean>
    
</beans>

測試程式碼也跟set和list類似

輸出:

{key1=value1, key2=value2}

 

Properties

配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <bean id="ci" class="com.rl.spring.model.CollectionInjection">
    <!-- 屬性set -->
        <property name="set">
            <set>
            <!-- 給集合賦值 -->
                <value>football</value>
                <value>basketball</value>
            </set>
        </property>
        
        <property name="map">
            <map>
                <entry key="key1" value="value1"></entry>
                <entry key="key2" value="value2"></entry>
            </map>
        </property>
        
        <property name="prop">
            <props>
                <prop key="name">lijialin</prop>
                <prop key="job">講師</prop>
            </props>
        </property>
    </bean>
    
</beans>

測試程式碼:

package com.rl.spring.test;

import java.util.Map;
import java.util.Properties;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rl.spring.model.CollectionInjection;

public class TestSpring {

	@Test
	public void test() {
		ApplicationContext ctx =
				new ClassPathXmlApplicationContext("ApplicationContext5.xml");
		CollectionInjection ci = (CollectionInjection) ctx.getBean("ci");
//		Set<String> set = ci.getSet();
//		Map<String, String> map = ci.getMap();
		Properties prop = ci.getProp();
		System.out.println(prop);
	}
}

輸出結果:

{name=lijialin, job=講師}

相關文章