1. 程式人生 > >Spring再接觸 註入類型

Spring再接觸 註入類型

三種 ati ng- ngs mls pro location classpath imp

共有三種註入類型 一種是set註入 一種是構造註入 一種是接口註入 最常用的還是set 現在看一下construct

構造註入

在userservice中加入

package com.bjsxt.service;
import com.bjsxt.dao.UserDAO;
import com.bjsxt.model.User;



public class UserService {
    
    private UserDAO userDAO;  
    public void add(User user) {
        userDAO.save(user);
    }
    
public UserDAO getUserDAO() { return userDAO; } public void setUserDAO(UserDAO userDAO) { this.userDAO = userDAO; } public UserService(UserDAO userDAO) { super(); this.userDAO = userDAO; } }

XML中

<?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-2.5.xsd"> <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl"> </bean> <bean id="
userService" class="com.bjsxt.service.UserService"> <!-- <property name="userDAO" ref="u" /> --> <constructor-arg> <ref bean="u"/> </constructor-arg> </bean> </beans>

測試代碼

    @Test
    public void testAdd() throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        
        
        UserService service = (UserService)ctx.getBean("userService");
        
        
        User u = new User();
        u.setUsername("zhangsan");
        u.setPassword("zhangsan");
        service.add(u);
    }

這樣也是可以成功註入impl的

Spring再接觸 註入類型