Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3402750
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T05:10:35+00:00 2026-05-18T05:10:35+00:00

I ran into an issue that can only be explained with my fundamental lack

  • 0

I ran into an issue that can only be explained with my fundamental lack of understanding of Spring’s IoC container facilities and context setup, so I would ask for clarification regarding this.

Just for reference, an application I am maintaing has the following stack of technologies:

  • Java 1.6
  • Spring 2.5.6
  • RichFaces 3.3.1-GA UI
  • Spring framework is used for bean management with Spring JDBC module used for DAO support
  • Maven is used as build manager
  • JUnit 4.4 is now introduced as test engine

I am retroactively (sic!) writing JUnit tests for the application and what suprised me is that I wasn’t able to inject a bean into a test class by using setter injection without resorting to @Autowire notation.

Let me provide set up an example and accompanying configuration files.

The test class TypeTest is really simple:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TypeTest {

    @Autowired
    private IType type;

    @Test
    public void testFindAllTypes() {
        List<Type> result;

        try {
            result = type.findAlltTypes();
            assertNotNull(result);
        } catch (Exception e) {
            e.printStackTrace();
            fail("Exception caught with " + e.getMessage());
        }
    }
}

Its context is defined in TestStackOverflowExample-context.xml:

<context:property-placeholder location="classpath:testContext.properties" />
<context:annotation-config />
<tx:annotation-driven />

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="${db.connection.driver.class}" />
    <property name="url" value="${db.connection.url}" />
    <property name="username" value="${db.connection.username}" />
    <property name="password" value="${db.connection.password}" />
</bean>

<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="beanDAO" class="com.example.BeanDAOImpl">
    <property name="ds" ref="dataSource"></property>
    <property name="beanDAOTwo" ref="beanDAOTwo"></property>
</bean>

<bean id="beanDAOTwo" class="com.example.BeanDAOTwoImpl">
    <property name="ds" ref="dataSource"></property>
</bean>

<bean id="type" class="com.example.TypeImpl">
    <property name="beanDAO" ref="beanDAO"></property>
</bean>

TestContext.properties is in classpath and contains only db-specific data needed for datasource.

This works like a charm but my question is – why doesn’t it work when I try to manually wire beans and perform setter injection as in:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TypeTest {

    private IType type;

    public IType getType () {
        return type;
    }

    public void setType(IType type) {
        this.type= type;
    }

    @Test
    public void testFindAllTypes(){
    //snip, snip...
    }
}

What am I missing here? What part of configuration is wrong here? When I try to manually inject beans via setters, test fails because this part

result = type.findAlltTypes();

is resolved as null in runtime. I’ve, of course, consulted the Spring reference manual and tried various combinations of XML configuration; all I could conclude is that Spring was unable to inject beans because it somehow fails to properly dereference Spring Test Context reference but by using @Autowired this happens “automagically” and I really can’t see why is that because JavaDoc of both Autowired annotation and its PostProcessor class doesn’t mention this.

Also worth adding is the fact that @Autowired is used in application only here. Elsewhere only manual wiring is performed, so this also brings forth question – why is it working there and not here, in my test? What part of DI configuration am I missing? How does @Autowired get reference of Spring Context?

EDIT:
I’ve also tried this but with same results:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TypeTest implements ApplicationContextAware{

    private IType type;

    private ApplicationContext ctx;

    public TypeTest(){
              super();
              ctx = new FileSystemXmlApplicationContext("/TypeTest-context.xml");
              ctx.getBean("type");
    }

    public IType getType () {
        return type;
    }

    public void setType(IType type) {
        this.type= type;
    }

    @Test
    public void testFindAllTypes(){
    //snip, snip...
    }
}

Any other ideas, perhaps?

EDIT2:
I’ve found a way without resorting to writing own TestContextListener or BeanPostProcessor. It is suprisingly simple and it turns out that I was on the right track with my last edit:

1) Constructor-based context resolving:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TypeTest{

    private IType type;

    private ApplicationContext ctx;

    public TypeTest(){
         super();
         ctx = new FileSystemXmlApplicationContext("/TypeTest-context.xml");
         type = ctx.getBean("type");
    }

    public IType getType () {
        return type;
    }

    public void setType(IType type) {
        this.type= type;
    }

    @Test
    public void testFindAllTypes(){
    //snip, snip...
    }
}

2) By implementing ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TypeTest implements ApplicationContextAware{

    private IType type;
    private ApplicationContext ctx;

    public IType getType () {
        return type;
    }

    public void setType(IType type) {
        this.type= type;
    }

@Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
    this.ctx = ctx;
    type = (Type) ctx.getBean("type");
}

    @Test
    public void testFindAllTypes(){
    //snip, snip...
    }
}

Both of these approaches properly instanced beans.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T05:10:35+00:00Added an answer on May 18, 2026 at 5:10 am

    If you take a look at the source of org.springframework.test.context.support.DependencyInjectionTestExecutionListener, you will see the following method (formatted and commented for clarity):

    protected void injectDependencies(final TestContext testContext)
    throws Exception {
        Object bean = testContext.getTestInstance();
        AutowireCapableBeanFactory beanFactory = testContext.getApplicationContext()
                .getAutowireCapableBeanFactory();
        beanFactory.autowireBeanProperties(bean, 
    
                AutowireCapableBeanFactory.AUTOWIRE_NO,
                // no autowiring!!!!!!!!
    
                false
            );
    
        beanFactory.initializeBean(bean, testContext.getTestClass().getName());
        // but here, bean post processors are run
    
        testContext.removeAttribute(REINJECT_DEPENDENCIES_ATTRIBUTE);
    }
    

    So the test object is a bean without auto-wiring. However, @AutoWired, @Resource etc, don’t use the autowiring mechanism, they use BeanPostProcessor. And so the dependencies are injected if and only if the annotations are used (or if you register some other BeanPostProcessor that does it).

    (The above code is from Spring 3.0.x, but I bet it was the same in 2.5.x)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I ran into an issue with something that I am probably just overlooking. I
I currently ran into the issue that I do not have the money to
I ran into an issue with an IIS web app shutting down an idle
This morning I ran into an issue with returning back a text string as
I recently ran into a issue where intermediate link betweeen a TCP server and
I just ran into an issue with Python's imaplib and Gmail's authentication mechanism: >>>
I ran into an interesting (and very frustrating) issue with the equals() method today
I ran into the problem that my primary key sequence is not in sync
I ran into an interesting behavior recently. It seems that if I override .equals()
Ran into this issue yesterday on one of our sites. First of all the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.