tom*_*ies 9 java service spring dependency-injection autowired
我需要通过@Autowired注入服务类的具体实现.
服务界面:
public interface PostService {
...
}
Run Code Online (Sandbox Code Playgroud)
执行:
@Service("postServiceImpl")
public class PostServiceImpl implements PostService {
...
}
Run Code Online (Sandbox Code Playgroud)
服务中的方法使用@Transactional注释
现在我想将postServiceImpl注入我的控制器 - 因为我需要使用实现中的一个方法,而不是在接口中:
@Autowired
@Qualifier("postServiceImpl")
private PostServiceImpl postService;
Run Code Online (Sandbox Code Playgroud)
我收到NoSuchBeanDefinitionException并带有以下消息:
没有为依赖项找到类型为[(...).PostServiceImpl]的限定bean:期望至少有一个bean可以作为此依赖项的autowire候选者.
当我将控制器中的字段更改为:
private PostService postService
Run Code Online (Sandbox Code Playgroud)
它工作,但我不能使用PostServiceImpl中的特定方法.
Roh*_*ain 10
由于您的方法已注释@Transactional
,spring将在运行时创建代理,以注入事务管理代码.默认情况下,Spring使用JDK动态代理进行代理机制,代理基于接口.
因此,在这种情况下,spring创建另一个实现PostService
接口的类,并创建该类的bean.绝对不能自动装配PostServiceImpl
,因为那些是兄弟姐妹.但是,如果你真的想在类上自动装配,你可以强制spring使用CGLib代理,代理使用子类.那你可以通过设置做proxyTargetClass=true
你的@EnableTransactionManagement
注释,如果你使用基于Java的配置.
归档时间: |
|
查看次数: |
4887 次 |
最近记录: |