Reputation: 21
I have a class.
public class Definitions{
@Resource(name="schemas")
private Collection<String> schemas;
}
This class is initialized via spring. Spring file:test.xml
<util:list id="schemas">
<value>"A"</value>
<value>"b"</value>
</util:list
<bean id="Definitions" />
Is there some way I can insert value to private field schemas(annotated with Resource) in my unit test without using spring. I tried using setting private variable via Reflection but that also did not help(probably due to security restrictions).
Even using spring, ApplicationContext context = new ClassPathXmlApplicationContext("test.xml"); It is not able to load schemas in Definitions bean. I get "NullPointerException" while accessing schemas.
Upvotes: 2
Views: 2532
Reputation: 1092
Try to do the following:
Insert the list in you spring.xml:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<util:list id="listTest">
<value>Valor 1</value>
<value>Valor 2</value>
</util:list>
</beans>
Reference the list in your code:
@Resource(name = "listTest")
private List<String> listTest;
I've tested here and it works fine on Spring 4 and 3, there's no need to implement a setter method.
Upvotes: 0
Reputation: 691755
Add a setter for it:
public class Definitions{
private Collection<String> schemas;
@Resource(name="schemas")
public void setSchemas(Collection<String> schemas) {
this.schemas = schemas;
}
}
This is the principle of dependency injection: you inject dependencies manually, vis constructor or setter injection, in your unit tests.
Upvotes: 1