简体   繁体   English

自动接线,无需组件扫描或设置器/获取器

[英]Autowired without component scan or setter/getter

Is it possible to @Autowired a field 是否可以@Autowired一个字段

@Repository( "categoryDao" )
public class SomeDaoImpl implements SomeDao {
   @Autowired
   private SessionFactory sessionFactory;
   ...
}

without using setter/getter or *component scan ? 不使用setter / getter* component scan

I have a config 我有一个配置

<bean id="categoryDao" class="com.example.dao.SomeDaoImpl">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    ...
</bean>

You can use constructor injection instead, so something like 您可以改用构造函数注入,所以类似

@Repository( "categoryDao" )
public class SomeDaoImpl implements SomeDao {

   private SessionFactory sessionFactory;

   @Autowired
   public SomeDaoImpl(SessionFactory sessionFactory) {
     this.sessionFactory = sessionFactory;
   }
   ...
}

There's a good discussion about the different types of injection, with a lot of refernce links available here 关于不同类型的注入有一个很好的讨论, 这里有很多参考链接

UPDATE after comment 评论后更新

Now that you explained, you should not change your code on accout of test. 既然您已经解释了,就不应该根据测试来更改代码。 In your case you should use a test specific XML context, but reduce the packages being scanned to just enough 在您的情况下,您应该使用特定于测试的XML上下文,但是将要扫描的包减少到恰到好处

Also a handy construct is that inside your test context xml, you can redifine some injected beans by instantiating it first and using context:exclude-filter property, usefull for mocking, an example snippet 另外一个方便的构造是,在测试上下文xml中,您可以通过首先实例化并使用context:exclude-filter属性(对context:exclude-filter有用)和示例片段来重新注入一些注入的bean。

<!--Mock object -->
<bean id="beanDAO" name="beanDAO" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="your.package.BeanDAO"/>
</bean>

<context:component-scan base-package="your.package">
    <context:exclude-filter type="regex" expression="your\.package\.Bean*"/>
</context:component-scan>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM