首页 > 代码库 > Spring初学之泛型依赖注入

Spring初学之泛型依赖注入

主要讲泛型依赖注入,所以核心在java文件,配置文件中只需配置扫描包即可,如下:

<?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-4.3.xsd">

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

</beans>
spring.beans.generic.di包中有两个配置的泛型的父类,有两个继承这两个父类的子类,还有一个实体bean,先看实体bean:
由于只是模拟一下,没必要写属性,创建一个类即可。
package spring.beans.generic.di;

public class User {

}

再看两个泛型的父类:

package spring.beans.generic.di;

public class BaseRepository<T> {

}

 

package spring.beans.generic.di;

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

public class BaseService<T> {
    @Autowired
    protected BaseRepository<T> repository;
    public void add(){
        System.out.println("add...");
        System.out.println(repository);
    }
}

子类:

package spring.beans.generic.di;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository extends BaseRepository<User>{

}

 

 

package spring.beans.generic.di;

import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User> {


}

 

测试:

package spring.beans.generic.di.test;

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

import spring.beans.generic.di.UserService;

public class Main {

    public static void main(String[] args) {

        ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-generic-di.xml");
        UserService userService=(UserService) ctx.getBean("userService");
        userService.add();//输出的是子类的对象
    }

}

输出:

add...
spring.beans.generic.di.UserRepository@8646db9

 

Spring初学之泛型依赖注入