Spring的编码方式——XML、注解、JavaConfig

Spring为我们提供了三种编码方式,Schema-based(XML)、Annotation-based(注解)和Java-based Container Configuration(JavaConfig),且三种方式可以混合使用,其中目前比较主流的是注解+JavaConfig混合使用。下面通过代码给大家展示三种编码方式分别如何实现。

首先为项目添加maven的pom依赖spring-context

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.2.RELEASE</version>
</dependency>

1、Schema-based(XML) 

package com.tyyd.ioc.xml.dao;

public interface PigDao {
    void test();
}
package com.tyyd.ioc.xml.dao;

public interface DogDao {
    void test();
}
package com.tyyd.ioc.xml.dao;

public interface CatDao {
    void test();
}
package com.tyyd.ioc.xml.dao.impl;

import com.tyyd.ioc.xml.dao.PigDao;

public class PigDaoImpl implements PigDao {

    private String str;

    private String str2;

    public void test() {
        System.out.println("PigDao: " + str);
        System.out.println("PigDao: " + str2);
    }

    public void setStr(String str) {
        this.str = str;
    }

    public void setStr2(String str2) {
        this.str2 = str2;
    }
}

 

package com.tyyd.ioc.xml.dao.impl;

import com.tyyd.ioc.xml.dao.CatDao;

public class CatDaoImpl implements CatDao {

    private String str;

    private String str2;

    public void test() {
        System.out.println("CatDao: " + str);
        System.out.println("CatDao: " + str2);
    }

    public void setStr(String str) {
        this.str = str;
    }

    public void setStr2(String str2) {
        this.str2 = str2;
    }
}
package com.tyyd.ioc.xml.dao.impl;

import com.tyyd.ioc.xml.dao.DogDao;

public class DogDaoImpl implements DogDao {

    private String str;

    private String str2;

    public void test() {
        System.out.println("DogDao: " + str);
        System.out.println("DogDao: " + str2);
    }

    public void setStr(String str) {
        this.str = str;
    }

    public void setStr2(String str2) {
        this.str2 = str2;
    }
}
package com.tyyd.ioc.xml.service;

public interface PigService {
    void test();
}
package com.tyyd.ioc.xml.service.impl;

import com.tyyd.ioc.xml.dao.CatDao;
import com.tyyd.ioc.xml.dao.DogDao;
import com.tyyd.ioc.xml.dao.PigDao;
import com.tyyd.ioc.xml.service.PigService;

public class PigServiceImpl implements PigService {

    private PigDao pigDao;

    private CatDao catDao;

    private DogDao dogDao;

    public PigServiceImpl(DogDao dogDao) {
        this.dogDao = dogDao;
    }

    public void test() {
        pigDao.test();
        catDao.test();
        dogDao.test();
    }

    public void setPigDao(PigDao pigDao) {
        this.pigDao = pigDao;
    }

    public void setCatDao(CatDao catDao) {
        this.catDao = catDao;
    }
}

 在项目的resource路径下新建一个XML,通过XML配置bean的依赖关系。

注:其实这个bean依赖关系的XML配置从程序设计角度看是多余的,因为我们自身定义的类(bean)已经定义好了依赖关系,而Spring也为我们提供了相应的解决手段,那就是自动装配,不过自动装配不在本文的讲解范围内,后续会另外通过一篇文章展开讲述。

<?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:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- spring xml 注入(对象和属性)有两种方式 property标签注入或者p:(注入的是属性)和c:前缀(构造方法 注入的是对象)注入 -->
    <!-- p: c:前缀注入还需在xml中加入xmln:c 和 xmlns:p -->
    <bean id="pigDao" class="com.tyyd.ioc.xml.dao.impl.PigDaoImpl" p:str="str">
        <!-- 引用的不是容器里的bean,使用value -->
        <property name="str2" value="str2" />
    </bean>

    <bean id="catDao" class="com.tyyd.ioc.xml.dao.impl.CatDaoImpl" p:str="str">
        <property name="str2" value="str2" />
    </bean>

    <bean id="dogDao" class="com.tyyd.ioc.xml.dao.impl.DogDaoImpl" p:str="str">
        <property name="str2" value="str2" />
    </bean>

    <bean id="service" class="com.tyyd.ioc.xml.service.impl.PigServiceImpl" c:dogDao-ref="dogDao">
        <!-- 引用的是容器里的对象,使用ref -->
        <property name="pigDao" ref="pigDao" />
        <property name="catDao" ref="catDao" />
    </bean>
</beans>

如上述代码所示,通过XML注入属性有两种方式,一是<property>标签,二是p:和c: ,其中要使用p:和c:,需要在XML头部加入如下代码:

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

p:是注入常规的属性值比如String,而c:是注入容器中的对象 。

package com.tyyd.ioc.test;

import com.tyyd.ioc.xml.service.impl.PigServiceImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath:spring-ioc.xml");
        PigServiceImpl pigService = (PigServiceImpl)classPathXmlApplicationContext.getBean("service");
        pigService.test();
    }
}

2、Annotation-based(注解)

注:其中@Component、@Service、@Repository、@Controller注解的效果一样,通过以上注解,将在容器中构造一个bean。@Componet可以理解为其他三个的父类。@Service作用于Service层,@Repository作用于Dao层,@Controller作用于控制层,这三个注解源码中都包含了@Component。虽然我们我们可以使用@Component代替其他两个注解,但Spring并不建议这样使用。因为Spring在官网上声明,按照其规范使用,这样可以明确地知道使用类的类型,另外避免后续Spring的注解变更影响到程序。

package com.tyyd.ioc.annotation.dao;

public interface PigDao {
    void test();
}
package com.tyyd.ioc.annotation.dao.impl;

import com.tyyd.ioc.annotation.dao.PigDao;
import org.springframework.stereotype.Repository;

@Repository
public class PigDaoImpl implements PigDao {
    public void test() {
        System.out.println("PigDao");
    }
}

 

package com.tyyd.ioc.annotation.service;

public interface PigService {
    void test();
}
package com.tyyd.ioc.annotation.service.impl;

import com.tyyd.ioc.annotation.dao.PigDao;
import com.tyyd.ioc.annotation.service.PigService;
import org.springframework.stereotype.Service;

@Service
public class PigServiceImpl implements PigService {

    private PigDao pigDao;

    public void test() {
        pigDao.test();
    }
}

 同样Resource路径下新建一个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:context="http://www.springframework.org/schema/context"
       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">
    <!-- 开启注解 在Spring 3或者4开始 已经不需要通过此代码开启注解配置 -->
    <!--<context:annotation-config></context:annotation-config>-->
    <context:component-scan base-package="com" />
</beans>

3、Java-based Container Configuration(JavaConfig)

package com.tyyd.ioc.javaconfig.dao;

public interface PigDao {
    void test();
}
package com.tyyd.ioc.javaconfig.dao.impl;

import com.tyyd.ioc.javaconfig.dao.PigDao;
import org.springframework.stereotype.Repository;

@Repository
public class PigDaoImpl implements PigDao {
    public void test() {
        System.out.println("PigDao");
    }
}

 

package com.tyyd.ioc.javaconfig.service;

public interface PigService {
    void test();
}
package com.tyyd.ioc.javaconfig.service.impl;

import com.tyyd.ioc.javaconfig.dao.PigDao;
import com.tyyd.ioc.javaconfig.service.PigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PigServiceImpl implements PigService {

    @Autowired
    private PigDao pigDao;

    public void test() {
        pigDao.test();
    }
}

 

package com.tyyd.ioc.javaconfig.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com")
public class JavaConfig {
}
package com.tyyd.ioc.test;

import com.tyyd.ioc.javaconfig.config.JavaConfig;
import com.tyyd.ioc.javaconfig.service.impl.PigServiceImpl;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(JavaConfig.class);
        PigServiceImpl service = (PigServiceImpl)annotationConfigApplicationContext.getBean("pigServiceImpl");
        service.test();
    }
}

以上三种编码风格可混合使用

package com.tyyd.dao;

/**
 *  测试DAO接口
 */
public interface IndexDao {
    /**
     * 测试方法
     */
    public void test();
}
package com.tyyd.dao.impl;

import com.tyyd.dao.IndexDao;
import com.tyyd.domain.Person;

/**
 *  测试接口实现类
 */
public class IndexDaoImpl implements IndexDao {

    private String str;

    private String str2;

    private Person person;

    /**
     * 测试接口
     */
    public void test() {
        System.out.println("impl");
        System.out.println(str);
        System.out.println(str2);
        System.out.println(person.getName());
        System.out.println(person.getAge());
    }

    public void setStr(String str) {
        this.str = str;
    }

    public void setStr2(String str2) {
        this.str2 = str2;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}
package com.tyyd.service;

/**
 *  测试Service
 */
public interface IndexService {
    /**
     *  测试方法
     */
    public void test();
}
package com.tyyd.service.impl;

import com.tyyd.dao.IndexDao;
import com.tyyd.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *  测试Sercice实现类
 */
//@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private IndexDao indexDao;

    /**
     * 测试方法
     */
    public void test() {
        indexDao.test();
    }

    /**
     * IOC Set方法注入
     * @param indexDao
     */
    public void setIndexDao(IndexDao indexDao) {
        this.indexDao = indexDao;
    }
}
package com.tyyd.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ComponentScan("com")
@ImportResource("classpath:spring-ioc.xml")
/**
 * 引入springXML文件 本项目为Spring注解 JavaConfig以及XML混合使用
 */
public class JavaConfig {

}
<?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:c="http://www.springframework.org/schema/c"
       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">
    <!-- 开启注解 Spring3或者4版本此代码已经可以省略不写 -->
    <!--<context:annotation-config ></context:annotation-config>-->

    <!-- 配置注解扫描路径(Spring3或者4版本中此代码已经包含开启注解) -->
    <!--<context:component-scan base-package="com" />-->

    <!-- IOC Set方法注入 -->
    <bean id="dao" class="com.tyyd.dao.impl.IndexDaoImpl" p:str2="str2">
         <!--注入非对象(bean)用value属性,注入bean用ref -->
        <property name="str" value="str"></property>
        <property name="person">
            <bean class="com.tyyd.domain.Person">
                <property name="name" value="Wang zhe xiao" />
                <property name="age" value="29" />
            </bean>
        </property>
    </bean>

    <!-- IOC Set方法注入 -->
    <!--<bean id="indexServiceImpl" class="com.tyyd.service.impl.IndexServiceImpl">-->
        <!--<property name="indexDao" ref="dao"></property>-->
    <!--</bean>-->
    <!--&lt;!&ndash; IOC 构造方法注入 &ndash;&gt;-->
    <!--<bean id="service" class="com.tyyd.service.impl.IndexServiceImpl" c:indexDao-ref="dao">-->
        <!--&lt;!&ndash;<constructor-arg ref="dao"></constructor-arg>&ndash;&gt;-->
    <!--</bean>-->

</beans>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值