spring 泛型依赖注入
一、代码实现
项目结构:
1 2 3 4 5 |
package generic; public class baserepository<T> { } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package generic; import org.springframework.beans.factory.annotation.Autowired; public class baseservice<T> { @Autowired protected baserepository<T> baserepository; public void add(){ System.out.println("add..."); System.out.println(baserepository); } } |
1 2 3 4 5 |
package generic; public class user{ } |
1 2 3 4 5 6 7 8 9 |
package generic; import org.springframework.stereotype.Repository; @Repository public class userrepository extends baserepository<user> { } |
1 2 3 4 5 6 7 8 9 |
package generic; import org.springframework.stereotype.Service; @Service public class userservice extends baseservice<user> { } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package generic; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class main { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans-generic.xml"); userservice userservice = (generic.userservice) applicationContext.getBean("userservice"); userservice.add(); } } |
运行结果:
1 2 |
add... generic.userrepository@1b279c9 |
成功获得泛型类。
二、注解和xml配置bean的优缺点
个人认为:
- 注解的话比较简单,写好bean,加上注解,配置xml中<context:component-scan base-package=”annotation”></context:component-scan>,就会自动扫描,成功注入。但是结构不如xml清晰,而且bean之间的关系需要@Autowired注解连接。
- xml的话比较复杂,需要掌握配置语法,并且容易出错。但是结构很清晰,bean之间的关系也很明显。
- 具体使用时,逻辑部分使用注解注入。配置部分使用xml注入。
三、总结
记录一下。