Spring4新特性泛型依賴注入
阿新 • • 發佈:2018-12-09
什麼叫做泛型依賴注入呢?
就是帶泛型的兩個父類他們之間有引用關係,
子類各自繼承他們,子類之間彼此之間也會有父類間的引用關係。
舉例:
兩個父類:之間有引用關係。
package one;
public class Respository<T> {
}
import org.springframework.beans.factory.annotation.Autowired;
public class Service<T> {
@Autowired
protected Respository<T> respository;
public void add(){
System.out.println("Add");
System.out.println(respository);
}
}
隨便建立個泛型例項類:
public class User {
}
兩個子類繼承父類:
import org.springframework.stereotype.Component;
@Component
public class UserRespository extends Respository<User> {
}
@Component
public class UserService extends Service<User> {
}
配置xml註解注入:
<context:component-scan base-package="one">
</context:component-scan>
測試:
public static void main(String[] args) throws SQLException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml" );
UserService five = (UserService) applicationContext.getBean("userService");
five.add();
}
輸出:
Add
one.UserRespository@799d4f69
可以看到子類也繼承了父類的引用關係,不過UserService中的引用類是Respository的實現類,即UserRespository類。
注意:
@Autowired註解是為了 引用關係,但是父類上不需要註解,其 實現類需要註解,交給IOC管理。