1. 程式人生 > >Spring 學習(十四)——泛型依賴注入

Spring 學習(十四)——泛型依賴注入

Spring 4.x 中可以為子類注入子類對應的泛型型別的成員變數的引用

整合多個配置檔案

Spring 允許通過 <import> 將多個配置檔案引入到一個檔案中,進行配置檔案的整合。這樣在啟動 Spring 容器時,僅需要指定這個合併好的配置檔案就可以。

import 元素的 resource 屬性支援 Spring 的標準的路徑資源

程式碼:

BaseRepository.java
package com.hzyc.spring.bean.generic.di;

/**
 * @author xuehj2016
 * @Title: BaseRepository
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/19 0:23
 */
public class BaseRepository <T> {
}
BaseService.java
package com.hzyc.spring.bean.generic.di;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author xuehj2016
 * @Title: BaseService
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/19 0:24
 */
public class BaseService<T> {
    @Autowired
    protected BaseRepository<T> repository;

    public void add() {
        System.out.println("add...");
        System.out.println("repository");
    }
}
UserRepository.java
package com.hzyc.spring.bean.generic.di;

import org.springframework.stereotype.Repository;

/**
 * @author xuehj2016
 * @Title: UserRepository
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/19 0:27
 */
@Repository
public class UserRepository extends BaseRepository<User> {
}

UserService .java 

package com.hzyc.spring.bean.generic.di;

import org.springframework.stereotype.Service;

/**
 * @author xuehj2016
 * @Title: UserService
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/19 0:26
 */
@Service
public class UserService extends BaseService<User> {
}

user.java

package com.hzyc.spring.bean.generic.di;

/**
 * @author xuehj2016
 * @Title: User
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/19 0:27
 */
public class User {
}

Main.java

package com.hzyc.spring.bean.generic.di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author xuehj2016
 * @Title: Main
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/19 0:30
 */
public class Main {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean-generic-di.xml");

        UserService userService= (UserService) applicationContext.getBean("userService");
        System.out.println(userService);
        userService.add();
    }
}

bean-generic-di.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">

    <context:component-scan base-package="com.hzyc.spring.bean.generic.di"/>

</beans>