Trying to set up a project but fail at Autowiring objects through Spring.
package se.hsr.web;
public class TestRunner {
public static void main(String[
You need this at the top of your test class:
@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml"
// in the root of the classpath
@ContextConfiguration(locations={"/applicationContext.xml", "/applicationContext-test.xml"})
public class MyTest {
I assumed JUnit4; my oversight.
You do need the context configuration tag in an application context somewhere, but I don't see anyplace in your code where you're actually opening an application context file and creating an ApplicationContext. Usually that's done in a set up method for your test. You'll have better luck if you actually create an ApplicationContext somewhere. Try reading the XML from your CLASSPATH in a setup method and see if that helps.
You need this in your Spring configuration for autowiring to work
xmlns:context="http://www.springframework.org/schema/context"
....
<context:annotation-config/>
you are creating the POJO outside of the spring context.
if you really want to be able to instanciate "manually", you can fix this, by adding <context:spring-configured />
to your configuration, and then annotating ContactDAOImpl
with @Configurable
You need to retrieve the ContactDAO instance from Spring context. You are initing yourself with new
keyword.
See the below link;
@Autowired annotation not able to inject bean in JUnit class
or if not unit test
ClassPathResource resource = new ClassPathResource("beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);
beanFactory.getBean("nameOfYourBean");
http://static.springsource.org/spring/docs/2.0.x/reference/beans.html
Add @Component/@Repository
to the DAO/DAOImpl.
In order to use Spring features (autowiring, call to post construct methods or aspects) you need to let Spring instanciate the instances instead of using new
.
For instance:
public static void main(String[] args) {
ApplicationContext context = AnnotationConfigApplicationContext("se.hsr.web")
ContactDAO cd = (ContactDAO)context.getBean("contactDAOImpl");
Contact contact = new Contact();
contact.setFirstname("Zorro");
cd.addContact(contact);
}
AnnotationConfigApplicationContext
will scan the classes in the classes in the se.hsr.web
package to for classes with Spring annotations. It requires Spring 3.0 to work. Before that you should add the following line in your applicationContext.xml
file:
<context:component-scan base-package="se.hsr.web" />