user425367
user425367

Reputation:

Spring set a property using a runtime object?

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>

Upvotes: 1

Views: 1250

Answers (1)

Roadrunner
Roadrunner

Reputation: 6801

  1. 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 session scoped beans instead.

  2. 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.

  3. If You have classes that have dependecies created inside the test class, than the @ContextConfiguration will be of no help here. You can use AnnotationConfigApplicationContext by creating inside the test class an inner @Configuration class and configure the service class using Spring Java Config.

i.e.:

@ContextConfiguration
public class RealTest extends AbstractTest {

    @Autowired
    private ApplicationContext appCtx;

    private Service service;

    @Before
    public void setUp() {
        AnnotationConfigApplicationContext testCtx = new AnnotationConfigApplicationContext();
        testCtx.setParent(this.appCtx);
        testCtx.register(RealTestCfg.class);
        testCtx.refresh();

        this.service = BeanFactoryUtils.beanOfType(testCtx, Service.class);
    }

    @Configuration
    public static class RealTestCfg {

        @Bean
        public Session session() {
            return AbstractTest.session;
        }

        @Bean
        public Service service() {
            return new Service();
        }
    }
}

The @ContextConfiguration and parent ApplicationContext is optional, if You don't have any other dependencies. And AbstractTest.session needs to be protected static, or have protected static accessor.

Upvotes: 0

Related Questions