Spring 中使用XML配置方式和使用註解方式實現DI

Spring容器給咱們提供了很好的環境,咱們只關注主要業務便可,其餘的無需關注太多。今天剛學的DIjava

DI(Dependency Injection):依賴注入spring

使用XML配置文件完成依賴注入數組

1.1普通屬性的注入app

  建立實體類:ide

package cn.spring.entity;

import java.io.Serializable;

/**
 * Created by accp on 2017/3/23.
 */
public class User implements Serializable {
    private String name;
    private String pwd;
    private Integer age;


    //帶參構造
    public User(String name, String pwd, Integer age) {
        this.name = name;
        this.pwd = pwd;
        this.age = age;
    }

    public User(String name, String pwd) {
        this.name = name;
        this.pwd = pwd;
    }

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                ", age=" + age +
                '}';
    }

   
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
View Code

 編寫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:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
    <!--屬性注入-->
    <bean id="user1" class="cn.spring.entity.User">
        <property name="name" value="張三"></property>
        <property name="age" value="18"></property>
    </bean>

</beans>
View Code

 測試類:this

 @Test
    /*屬性注入*/
    public void firstTest(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        User user=(User)ctx.getBean("user1");
        System.out.println(user);
    }
View Code

 運行結果:spa

 

1.1.2域屬性的注入prototype

  建立實體類3d

package cn.spring.entity;

import java.io.Serializable;

/**
 * Created by accp on 2017/3/23.
 */
public class User implements Serializable {
    private String name;
    private String pwd;
    private Integer age;

    private Car myCar;

    public User(String name, String pwd, Car myCar) {
        this.name = name;
        this.pwd = pwd;
        this.myCar = myCar;
    }

    public User(String name, String pwd, Integer age, Car myCar) {
        this.name = name;
        this.pwd = pwd;
        this.age = age;
        this.myCar = myCar;
    }


    //帶參構造
    public User(String name, String pwd, Integer age) {
        this.name = name;
        this.pwd = pwd;
        this.age = age;
    }

    public User(String name, String pwd) {
        this.name = name;
        this.pwd = pwd;
    }

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                ", age=" + age +
                ", myCar=" + myCar +
                '}';
    }

    public Car getMyCar() {
        return myCar;
    }

    public void setMyCar(Car myCar) {
        this.myCar = myCar;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
View Code

 

package cn.spring.entity;

/**
 * Created by accp on 2017/3/23.
 */
public class Car {
    private String color;

    public Car() {
    }

    public Car(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Car{" +
                "color='" + color + '\'' +
                '}';
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}
View Code

編寫xml文件

 <!--域屬性注入-->
    <bean id="mmCar" class="cn.spring.entity.Car">
        <property name="color" value="green color"></property>
     </bean>

    <bean id="user4" class="cn.spring.entity.User">
        <property name="name" value="王小二"></property>
        <property name="age" value="10"></property>
        <property name="myCar" ref="mmCar"></property>
    </bean>
View Code

測試類

 @Test
    /*域屬性注入*/
    public void fourTest(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        User user=(User)ctx.getBean("user4");
        System.out.println(user);
    }
View Code

運行結果:

1.2構造注入

這個示例仍是借用上面建立的實體類,實體類的構造已建立完成,接下來就編寫xml文件

xml文件

<!--構造注入-->
    <bean id="user2" class="cn.spring.entity.User">
        <constructor-arg index="0" value="李四"></constructor-arg>
        <constructor-arg index="1" value="123"></constructor-arg>
      <!--  <constructor-arg index="2" value="16"></constructor-arg>-->
    </bean>
View Code

編寫測試類

 @Test
    /*構造注入*/
    public void secondTest(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        User user=(User)ctx.getBean("user2");
        System.out.println(user);
    }
View Code

運行結果

1.2.2構造注入域屬性

  注入域屬性與普通屬性注入域屬性的方式是一致的,咱們只需簡單的更改代碼便可。

 xml文件編寫

  <!--構造注入域屬性-->
    <bean id="mmCar1" class="cn.spring.entity.Car">
        <property name="color" value="red color"></property>
    </bean>

    <bean id="user5" class="cn.spring.entity.User">
        <constructor-arg index="0" value="小二"></constructor-arg>
        <constructor-arg index="1" value="6375196"></constructor-arg>
        <!--  <constructor-arg index="2" value="16"></constructor-arg>-->
        <constructor-arg index="2" ref="mmCar1"></constructor-arg>
    </bean>
View Code

 編寫測試類

 @Test
    /*構造注入域屬性*/
    public void fiveTest(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        User user=(User)ctx.getBean("user5");
        System.out.println(user);
    }
View Code

 

1.3使用p命名空間注入

  使用p命名空間注入時,須要注意的是:須要引入

   

 如上圖所示的命名空間。

 xml文件編寫

<!--p空間注入 直接注入值 -->
    <bean id="user3" class="cn.spring.entity.User" p:name="王五" p:age="14" p:myCar="myCar"></bean><!-- p:myCar="red"-->

還有一種方式:

 <!--p空間注入 引用bean -->
    <!--<bean id="user3" class="cn.spring.entity.User" p:name="王五" p:age="14" p:myCar-ref="mmCar" ></bean>-->

一共兩種方式,均可以實現p命名空間的注入。

編寫測試類

 @Test
    /*p空間注入*/
    public void thirdTest(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        User user=(User)ctx.getBean("user3");
        System.out.println(user);
    }
View Code

 運行結果

 

1.4集合注入

  集合注入分爲:array  list  set map properties 注入

 在這裏咱們就不舉例array的示例了,簡單的把其餘的實例演示一下。

 建立實體類

package cn.spring.entity;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Created by accp on 2017/3/23.
 */
public class CollectionBean {

    /**
     * 數組
     * List
     * Map
     * Set
     * properties
     *
     */

    private List<String> list;

    private Set<String> set;

    private Map<String,String> map;

    private Properties properties;

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

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

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

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }
}
View Code

編寫xml文件

    @Test
    /*list集合注入*/
    public void sexTest01(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        CollectionBean bean=(CollectionBean)ctx.getBean("collectionBean");
        System.out.println(bean.getList());
      
    }

    @Test
    /*set集合注入*/
    public void sexTest02(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
       
        //set集合
        CollectionBean bean=(CollectionBean)ctx.getBean("collectionBean2");
        System.out.println(bean.getSet());
    }

    @Test
    /*map集合注入*/
    public void sexTest03(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        //map集合
        CollectionBean bean=(CollectionBean)ctx.getBean("collectionBean3");
        System.out.println(bean.getMap().values()); //value值
        System.out.println(bean.getMap().keySet()); //key值
    }
    
    @Test
    /*properties 注入*/
    public void setTest04(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        CollectionBean bean=(CollectionBean)ctx.getBean("properties");
        System.out.println(bean.getProperties());
    }
View Code

編寫測試類

  @Test
    /*list集合注入*/
    public static void sexTest01(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        CollectionBean bean=(CollectionBean)ctx.getBean("collectionBean");
        System.out.println(bean.getList()+"==========list");

    }

    @Test
    /*set集合注入*/
    public static void sexTest02(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");

        //set集合
        CollectionBean bean=(CollectionBean)ctx.getBean("collectionBean2");
        System.out.println(bean.getSet()+"==========set");
    }

    @Test
    /*map集合注入*/
    public static void sexTest03(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        //map集合
        CollectionBean bean=(CollectionBean)ctx.getBean("collectionBean3");
        System.out.println(bean.getMap().values()+"==========map"); //value值
        System.out.println(bean.getMap().keySet()); //key值
    }

    @Test
    /*properties 注入*/
    public static void sexTest04(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        CollectionBean bean=(CollectionBean)ctx.getBean("properties");
        System.out.println(bean.getProperties()+"==========properties");
    }
View Code

運行結果

 

1.5使用註解的方式

使用註解方式實現值的注入須要導入命名空間

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">

以上的文件約束中的context爲註解須要導入的命名空間。

在編寫xml文件時只須要加入包掃描器便可。

xml文件編寫

 <!--註解配置包掃描器-->
    <context:component-scan base-package="cn.spring.note"></context:component-scan>

建立實體類

package cn.spring.note;

import cn.spring.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by accp on 2017/3/23.
 */
//Component  :不分包
//Service: biz層
//Controller: action
//Repository: biz
@Component("person")
public class Person {
    @Value("張三")
    private String name;
    @Value("18")
    private Integer age;

    @Autowired
    @Qualifier("car")
    private Car myCar;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", myCar=" + myCar +
                '}';
    }

    public Person() {
    }

    public Car getMyCar() {
        return myCar;
    }

    public void setMyCar(Car myCar) {
        this.myCar = myCar;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
View Code

Car編寫

package cn.spring.note;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Created by accp on 2017/3/23.
 */
@Component("car")
@Scope("prototype")
/*@Scope("singleton")*/
public class Car {

    @Value("red")
    private String color;

    @Override
    public String toString() {
        return "Car{" +
                "color='" + color + '\'' +
                '}';
    }

    public Car() {
        System.out.println("開始建立");
    }

    public Car(String color) {
        this.color = color;
    }
}
View Code

 編寫測試類(自身屬性注入)

 @Test
    /*註解自身屬性*/
    public void sevenTest(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContextXml.xml");
        Person person=(Person) ctx.getBean("person");
        System.out.println(person);
    }
View Code

運行結果

 

編寫測試類(關聯屬性注入)

@Test
    /*註解關聯對象*/
    public void eightTest(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContextXml.xml");
        Person person=(Person) ctx.getBean("person");
        System.out.println(person);
    }
View Code

運行結果

 

1.5.1使用註解實現多例

package cn.spring.note;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Created by accp on 2017/3/23.
 */
@Component("car")
@Scope("prototype")
/*@Scope("singleton")*/
public class Car {

    @Value("red")
    private String color;

    @Override
    public String toString() {
        return "Car{" +
                "color='" + color + '\'' +
                '}';
    }

    public Car() {
        System.out.println("開始建立");
    }

    public Car(String color) {
        this.color = color;
    }
}

編寫測試類

 @Test
    /*註解實現多例*/
    public void nineTest(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContextXml.xml");
        Car car=(Car) ctx.getBean("car");
        Car car2=(Car) ctx.getBean("car");
        System.out.println(car);
        System.out.println(car2);
    }
View Code

 

1.5.2註解實現加強

  建立實體類

package cn.spring.entity;

import java.io.Serializable;

/**
 * Created by accp on 2017/3/23.
 */
public class User implements Serializable {
    private String name;
    private String pwd;
    private Integer age;

    private Car myCar;

    public User(String name, String pwd, Car myCar) {
        this.name = name;
        this.pwd = pwd;
        this.myCar = myCar;
    }

    public User(String name, String pwd, Integer age, Car myCar) {
        this.name = name;
        this.pwd = pwd;
        this.age = age;
        this.myCar = myCar;
    }


    //帶參構造
    public User(String name, String pwd, Integer age) {
        this.name = name;
        this.pwd = pwd;
        this.age = age;
    }

    public User(String name, String pwd) {
        this.name = name;
        this.pwd = pwd;
    }

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                ", age=" + age +
                ", myCar=" + myCar +
                '}';
    }

    public Car getMyCar() {
        return myCar;
    }

    public void setMyCar(Car myCar) {
        this.myCar = myCar;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
View Code

Car類

package cn.spring.entity;

/**
 * Created by accp on 2017/3/23.
 */
public class Car {
    private String color;

    public Car() {
    }

    public Car(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Car{" +
                "color='" + color + '\'' +
                '}';
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}
View Code

建立DAO

package cn.spring.dao;

import cn.spring.entity.User;

/**
 * Created by accp on 2017/3/24.
 */
public interface UserDao {
    public void  save(User user);
}
View Code

建立DAOImpl

package cn.spring.dao.impl;

import cn.spring.dao.UserDao;
import cn.spring.entity.User;

/**
 * Created by accp on 2017/3/24.
 */
public class UserDaoImpl implements UserDao {
    public void save(User user) {
        System.out.println("開始保存用戶");
    }
}
View Code

建立Biz

package cn.spring.biz;

import cn.spring.entity.User;

/**
 * Created by accp on 2017/3/24.
 */
public interface UserBiz {
    public void save(User user);
}
View Code

建立BizImpl

package cn.spring.biz.impl;

import cn.spring.biz.UserBiz;
import cn.spring.dao.UserDao;
import cn.spring.entity.User;

/**
 * Created by accp on 2017/3/24.
 */
public class UserBizImpl implements UserBiz {
    private UserDao dao;
    public void save(User user) {
        dao.save(user);
    }

    public UserDao getDao() {
        return dao;
    }

    public void setDao(UserDao dao) {
        this.dao = dao;
    }
}
View Code

建立攔截類

package cn.spring.noteen;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/**
 * Created by accp on 2017/3/24.
 * 註解加強
 */
@Aspect
public class UserBizLogger {
    @Before("execution(* *..biz.*.*(..))")
    public void before(){
        System.out.println("註解方法加強開始");
    }
    @AfterReturning("execution(* *..biz.*.*(..))")
    public void after(){
        System.out.println("註解方法加強結束");
    }


}
View Code

xml配置文件

<!--註解方式的方法加強-->
    <bean id="userDao" class="cn.spring.dao.impl.UserDaoImpl"></bean>

    <bean id="userBiz" class="cn.spring.biz.impl.UserBizImpl">
        <property name="dao" ref="userDao"></property>
    </bean>
    <aop:aspectj-autoproxy/>
    <bean class="cn.spring.noteen.UserBizLogger"/>
View Code

測試類

 @Test
    /*使用註解方式定義方法加強*/
    public void tenTest(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserBiz biz=(UserBiz)ctx.getBean("userBiz");
        biz.save(new User());
    }
View Code

運行結果

相關文章
相關標籤/搜索