seo站长工具 论坛,苏州网页制作人才招聘,做一个网站的完整教程,能交易的网站多少钱用Autowired注解注入,写接口名字还是实现类的名字
来自某程序员一个问答问题
有一点没明白#xff0c;为什么注解repository注解的是接口UserDAO的实现类UserDAOImpl#xff0c;而在UserServiceImpl中使用Autowired注解注入属性private UserDAO userDAO自动装配#xff0c…用Autowired注解注入,写接口名字还是实现类的名字
来自某程序员一个问答问题
有一点没明白为什么注解repository注解的是接口UserDAO的实现类UserDAOImpl而在UserServiceImpl中使用Autowired注解注入属性private UserDAO userDAO自动装配为什么最后得到的是UserDAOImpl的实例。
-----上面是某位同学的提问我也有这样的疑问----
Service注解服务层的时候在unitest中是从ApplicationContext.getBean(“实现类名字首字母小写”) 这样获取的。
也就是说在容器中初始化的Bean应该按照实现类名字规则。 这一点如果是用xml配置是不存在这样的问题因为xml可以指定id, id 是接口class指向实现类。
来自网友的回答这个其实是创建了实现类的对象但引用了接口类型即InjectionDao injectionDao new InjectionDaoImpl(), 这个其实是Java多态性向上转型的一种应用。在实现类处加Repository注解意思就是new InjectionDaoImpl(), 而在InjectionServiceImpl中定义属性InjectionDAO injectionDAO就是将new出来的这个InjectionDaoImpl对象向上转型为InjectionDao类型。
Spring中Autowired注入接口的几个问题
1.Spring怎么知道注入哪个实现 As long as there is only a single implementation of the interface and that implementation is annotated with Component with Spring’s component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file). 如果Spring配置了component scan并且要注入的接口只有一个实现的话那么spring框架可以自动将interface于实现组装起来。如果没有配置component scan那么你必须在application-config.xml或等同的配置文件定义这个bean。
可以理解为 在 application-service.xml 配置文件中声明了 component-scan
context:component-scan base-packagecom.system.service.impl/在 com.system.service 下有一个接口类在 com.system.service.impl 下有一个接口对应的实现类且该实现类用 Service 注解进行了标注。
在使用该接口类的时候可以按照如下方式
Autowired
private UserloginService userloginService;以此来进行自动装配。
2.需要Qualifier和Resource注解吗 Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the Qualifier annotation to inject the right implementation, along with Autowired annotation. If you are using Resource (J2EE semantics), then you should specify the bean name using the name attribute of this annotation. 一旦一个接口有多个实现那么就需要每个特殊化识别并且在自动装载过程中使用Qualifier和Autowired一起使用来标明。如果是使用Resource注解那么你应该使用resource中属性名称来标注Autowired.
3.为什么Autowired使用在interface上而不是实现类上 Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage. 首先一般使用接口是很常用并且有益的变成技术。
其次在spring中你可以在运行过程中注入各种实现。一个很经典的情况就是在测试阶段注入模拟的实现类。
SpringBoot使用Autowired为多实现的接口注入依赖彻底理解Spring注解Autowired实现原理详解Spring依赖注入AutowiredResource和Inject区别与实现原理Spring详细讲解Autowired注解Spring的Autowired加到接口上但获取的是实现类的问题