1. 程式人生 > >Spring註入(IOC):

Spring註入(IOC):

str out int -i 一個個 mls cst inter isp

簡單來說就是減少層與層之間的耦合關系,本來在service調用dao要new,有了這個就可以通過註入的方式,相當與把所有的new操作都變成了在配置文件中配置,有改動時直接改配置就行了不用一個個java文件去改。

1.搭建web項目,導入spring核心包。copy到web目錄lib即可。

技術分享

項目的構成:

技術分享

1.首先是創建一個bean。省略setter、getter

public class UserBean{
    private String userName;
    private int age;
    private Date birthday;
    private double salary;
}

建立spring的配置文件application.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" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop
="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
> <import resource="application2.xml"/> <bean id="UserBean" class="pojo.UserBean" scope="singleton" lazy-init="true"> <!-- singleton – 單例模式 ,即整個應用只有一個實例 。適合於服務 bean 和Dao Bean。單例模式的對象實例在容器啟動時候就會創建。 ? Prototype – 原型模式,即每次請求都創建一個對象。適合於action bean。原型模式的對象在請求對象時候創建 lazy-init - 懶加載,默認=false,啟動就創建(不懶),true就是懶加載 --> <property name="userName" value="zs"></property> <property name="age" value="18"></property> <property name="birthday"> <bean class="java.util.Date"></bean> </property> <property name="salary" value="9000.33"></property> </bean> </beans>

單元測試,通過配置文件獲得創建的對象。兩種方式獲得。都能打印出結果。

public class UserBeanTest {

    @Test
    public void test() {
        //啟動spring 容器,指定配置文件。
        ApplicationContext ctx=new ClassPathXmlApplicationContext("application.xml");
        //通過容器獲取UserBean對象
        UserBean bean=(UserBean) ctx.getBean("UserBean");
        System.out.println(bean.toString());
    }
    @Test
    public void testByFactory(){
        //通過工廠類得到bean對象
        Resource resource= new ClassPathResource("application.xml");
        BeanFactory factory=new XmlBeanFactory(resource);
        //通過容器獲取UserBean對象
        UserBean bean=(UserBean) factory.getBean("UserBean");
        System.out.println(bean.toString());
    }


}

結果:

UserBean [userName=zs, age=18, birthday=Wed Sep 13 16:37:20 CST 2017, salary=9000.33]

2.對象的註入。

新建dao和impl

public interface UserDao {
    public abstract void print();

}


----------------------------------------------------------------------------------------
public class UserDaoImpl implements UserDao {
    @Override
    public void print() {
        System.out.println("dao打印:");
    }

    
}

新建service和impl

public interface UserService {
    public abstract void print();

}


-------------------------------------------------------------------------------------------
public class UserServiceImpl implements UserService {
    //要註入它
    UserDao dao;
    @Override
    public void print() {
        dao.print();
    }
    public UserDao getDao() {
        return dao;
    }
    public void setDao(UserDao dao) {
        this.dao = dao;
    }
    

}

建立配置文件2號

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

    <!-- set註入:對應在服務層調用dao給它setter、getter -->
    <bean id="dao" class="dao.impl.UserDaoImpl"></bean>
    <bean id="service" class="service.impl.UserServiceImpl">
        <property name="dao" ref="dao"></property>
    </bean>
    
    <!-- 內部bean方式,也要setter、getter -->
    <bean id="service2" class="service.impl.UserServiceImpl">
        <property name="dao">
            <bean class="dao.impl.UserDaoImpl"></bean>
        </property>
    </bean>    
    
    <!--P:命名空間註入屬性值 也要setter、getter,跟set註入一樣的,就是減少了property的數量。p:dao-ref="dao" 中的‘dao‘換為對應的註入對象即可-->
    <bean id="service3" class="service.impl.UserServiceImpl" p:dao-ref="dao"></bean>
    
    <!--自動註入(autowire)  -->
    <bean id="service4" class="service.impl.UserServiceImpl" autowire="byName"></bean>
    <!--?Aotowire=byType:根據名稱屬性類型自動進行註入。  -->
    <bean id="service5" class="service.impl.UserServiceImpl" autowire="byType"></bean>

</beans>

在原來的配置文件中加上import把兩個連接起來。

<import resource="application2.xml"/>

單元測試。

public class 各種註入方式 {

    @Test
    public void test() { //set註入
        /** application.xml 要import */
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
        /** 合並的寫法 */
//        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(new String[]{"application.xml","application2.xml"}); 
        UserService service= (UserService) applicationContext.getBean("service");
        service.print();
    }
    @Test
    public void test2() { //內部bean
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
        UserService service= (UserService) applicationContext.getBean("service2");
        service.print();
    }
    @Test
    public void test3() { //命名空間註入
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
        UserService service= (UserService) applicationContext.getBean("service3");
        service.print();
    }
    @Test
    public void test4() { //按照名字自動註入
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
        UserService service= (UserService) applicationContext.getBean("service4");
        service.print();
    }
    @Test
    public void test5() { //按照類型自動註入
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
        UserService service= (UserService) applicationContext.getBean("service5");
        service.print();
    }
    @Test
    public void test6() { //獲取bean的另一個寫法,會自動在配置文件中找對應的class類型匹配,但是配置文件裏面自能有一個對應的類,多了也錯
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
        UserService service= (UserService) applicationContext.getBean(UserService.class);
        service.print();
    }

}

test6這種獲取bean的方式要只有一個才可以,很多個bean都是一樣的,僅僅是id不同會報錯的。

3.註解方式。

Spring註入(IOC):