spring泛型依赖注入
Spring4.x中可以为子类注入子类对应的泛型类型的成员变量的引用。
假设有两个基类,BaseService和BaseRepository,
BaseService与BaseRepository之间有一个引用关系,BaseService可以调用BaseRepository里面已经定义好的的方法
假设BaseService有一个子类UserService,BaseRepository有一个子类UserRepository,
在继承时,父类BaseService<T>和BaseRepository<T>会提供一个泛型T,假设这个T是User,
那么,UserService和UserRepository这两个子类会自动继承父类之间的引用关系。
下面给出示例:
注意:要额外添加spring-aop-4.0.0.RELEASE.jar包
BaseRepository.java
package com.wul.spring.beans.generic.di;
public class BaseRepository<T>{
}
BaseService.java
package com.wul.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);
}
}
User.java
package com.wul.spring.beans.generic.di;
public class User {
}
UserRepository.java
package com.wul.spring.beans.generic.di;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository extends BaseRepository<User>{
}
UserService.java
package com.wul.spring.beans.generic.di;
import org.springframework.stereotype.Service;
@Service
public class UserService extends BaseService<User>{
}
Main.java
package com.wul.spring.beans.generic.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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();
}
}
beans-generic-di.xml
package com.wul.spring.beans.generic.di;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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();
}
}