Spring入門學習(泛型依賴注入) 第十三節
阿新 • • 發佈:2019-01-06
Spring入門學習(泛型依賴注入)
Spring4泛型依賴注入
- 建立泛型類
BaseRepository<T>
,BaseService<T>
,BaseService
中注入了BaseRepository<T>
類的beanpublic class BaseRepository<T> { }
public class BaseService<T> { @Autowired private BaseRepository<T> baseRepository;
- 建立
User
類,UserService
類,UserRepository
類,並添加註解:public class User { } @Service public class UserService extends BaseService<User> { } @Repository public class UserRepository extends
- 建立一個bean配置檔案
beans-generic-di.xml
<?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=
- 建立測試類:
測試結果:public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:beans-generic-di.xml"); UserService userService = (UserService) ctx.getBean("userService"); userService.add(); } }
此時BaseRepository add.... [email protected]
baseRepository
的bean是一個UserRepository
的bean