Spring - 泛型依赖注入(9)

2020-03-17 18:25:56 浏览数 (1)

spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用

代码语言:javascript复制
@Service
public class UserService extends BaseService<User> {}
代码语言:javascript复制
public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) ctx.getBean("userService");
        System.out.println(userService);
        userService.add();
    }
}
代码语言:javascript复制
public class BaseService<T> {
    @Autowired
    protected BaseRepository<T> repository;

    public void add(){
        System.out.println("add...");
        System.out.println(repository);
    }
}
代码语言:javascript复制
public class BaseRepository<T> { }
代码语言:javascript复制
@Repository
public class UserRepository extends BaseRepository<User> {
    @Override
    public String toString() {
        System.out.println("UserRepository");
        return super.toString();
    }
}
代码语言:javascript复制
public class User { }

0 人点赞