Is it possible to @Autowired
a field
@Repository( "categoryDao" )
public class SomeDaoImpl implements SomeDao {
@Autowired
private SessionFactory sessionFactory;
...
}
without using setter/getter or *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
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
<!--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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.