I have a hard time figuring out how to set a property with the help of spring annotations.
I have an abstract base class.
abstract class AbstractTest{
private static Session session;
@BeforeClass
public static void initApplication() throws Exception {
session = new Session();
...
}
public Session getSession(){
I have an test class extending my AbstractTest.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class RealTest extends AbstractTest{
@Autowired
Service service;
I have a service that needs to make use of the session object and I want it to be “autoset” to the session object.
public class ServiceImpl implements Service {
// @AutoSomething how to make this work?
private Session session;
The spring file that is automatically used for my RealTest thanks to the @ContextConfiguration Annotation
<bean id="Service" class="...ServiceImpl" >
<property name="session">
getSession()?? // What's the syntax or how to do this?
</property>
Read about bean scopes. It doesn’t really make sence the kind of injection You’re trying to do. You should not inject the session itself to the business service classes. You should use the
sessionscoped beans instead.The test class itself is not a part of the test ApplicationContext, so You cannot autowire the values created in the test class to the test class. Anyway, why would You do that? You already have it in the test class, so why not just use simple setter in
@Before public void setUp() {}method? Or see the next point.If You have classes that have dependecies created inside the test class, than the
@ContextConfigurationwill be of no help here. You can use AnnotationConfigApplicationContext by creating inside the test class an inner@Configurationclass and configure the service class usingSpring Java Config.i.e.:
The
@ContextConfigurationand parentApplicationContextis optional, if You don’t have any other dependencies. AndAbstractTest.sessionneeds to beprotected static, or haveprotected staticaccessor.