天天看點

Spring-控制反轉

1.建立項目

    項目名稱:spring092601

2.引入spring jar包

    commons-logging.jar

    junit-4.4.jar

    log4j.jar

    spring-beans-3.2.0.RELEASE.jar

    spring-context-3.2.0.RELEASE.jar

    spring-core-3.2.0.RELEASE.jar

    spring-expression-3.2.0.RELEASE.jar

3.添加配置檔案

    在conf下添加spring的核心配置檔案applicationContext.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:util="http://www.springframework.org/schema/util"

           xsi:schemaLocation="

    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    </beans>

4.建立業務bean

    在src目錄下建立

    包名:cn.jbit.spring092601.domain

    /**

     * spring入門

     * @author Administrator

     *

     */

    public class HelloSpring implements Serializable {

        private String name;

        public HelloSpring() {

            System.out.println("調用無參構造方法");

        }

        public HelloSpring(String name) {

            super();

            this.name = name;

        public void setName(String name) {

            System.out.println("set");

        public String getName() {

            System.out.println("get");

            return name;

    }

5.在配置檔案中編寫bean的配置,也就是我們的IOC(Inversion of Control)控制反轉

    配置如下:

        <!-- spring入門

            控制反轉IOC

            預設構造方法裝配Bean

         -->

        <bean id="helloSpring" class="cn.jbit.spring092601.domain.HelloSpring">

        </bean>

6.測試bean的配置

    在test目錄下測試

    public class HelloSpringTest {

        /**

         * 控制反轉方式實作

         * IOC方式

         */

        @Test

        public void testHellpSpring2(){

            /*

             * 對象由spring建立

             */

            ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

            HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");

            helloSpring.setName("張三");

            System.out.println(helloSpring.getName());

Spring-控制反轉
上一篇: 依賴注入
下一篇: 依賴注入