Spring – 泛型依赖注入(9)
- 2020 年 3 月 17 日
- 筆記
spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用
@Service public class UserService extends BaseService<User> {}
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(); } }
public class BaseService<T> { @Autowired protected BaseRepository<T> repository; public void add(){ System.out.println("add..."); System.out.println(repository); } }
public class BaseRepository<T> { }
@Repository public class UserRepository extends BaseRepository<User> { @Override public String toString() { System.out.println("UserRepository"); return super.toString(); } }
public class User { }