Why can't spring find my bean?

I created an interface and a class:

public interface UserService {
    List<User> listAll();
}

@Transactional
public class DefaultUserService implements UserService {
    private String tableName;
    public List<User> listAll() { someDao.listAllFromTable(tableName); }
    public void setTableName(String tableName) { this.tableName = tableName; }
}

Also in my xml context of the application file, context.xmlI defined:

<bean id="userService" class="mypackage.DefaultUserService">
    <property name="tableName" value="myusers" />
</bean>

Then I want to test DefaultUserService:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:context-test.xml"})
@TransactionConfiguration(transactionManager = "testTransactionManager")
@Transactional
public class UserServiceTest {

    @Autowired
    private DefaultUserService userService;

    @Before
    public void setup() {
        userService.setTableName("mytesttable");
    }
    @Test
    public void test() {
        // test with userService;
        userService.listAll();
    }
}

Note that it uses context-test.xmlthat imported the original context.xml:

<import resource="classpath:context.xml"/>

Unfortunately, when running the test, the spring exception throws:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'mypackage.UserServiceTest': 
Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: 
private mypackage.DefaultUserService mypackage.userService

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [mypackage.DefaultUserService] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this dependency. 
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I'm not sure where is wrong, why spring cannot find the bean DefaultUserServicethat I defined?

+4
source share
3 answers

, @Transactional bean - jdk, UserService, bean UserService, DefaultUserService. . fooobar.com/questions/1502832/....

@Value("${someprop}") , setTableName(), .

, - , , bean Spring Spring beans unit test

+2

DefaultUserService UserService

public class UserServiceTest {

    @Autowired
    private UserService userService;
    ....

}
+2

You have not defined getterfor your property tableNamein the implementing class.Spring container IOCfor the modelPOJO

+1
source

All Articles