Back Forum Reply New

How to use @Resource?

I am using JDK 1.6.0_05, Spring 2.5.2.

At first, my applicationContext.xml doesn't have the
Code:
xmlns:context=quot;schema/contextquot;
nor the
Code:
lt;context:annotation-config/gt;and my test class which uses JUnit4 looks like this

Code:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {quot;/applicationContext.xmlquot;})
public class DaoImplTest {   private final Log log = LogFactory.getLog(getClass());
   // this is called field injection, i.e. no need of a setter method   @Resource(name = quot;groupDaoquot;)   private GroupDao groupDao;
   @Resource(name = quot;contactDaoquot;)   private ContactDao contactDao;
   @Test   public void testGroupDaoImpl() { ...   // no need of setter methods for fields with @Resourceand the @Resource works perfectly.

Then I use @Resource in a normal Spring-managed bean (which is not a test class) and it doesn't work even though my applicationContext.xml has this:

Code:
lt;beans xmlns=quot;schema/beansquot;      xmlns:xsi=quot;2001/XMLSchema-instancequot;      xmlns:context=quot;schema/contextquot;      xsi:schemaLocation=quot;schema/beans          schema/beans/spring-beans-2.5.xsd          schema/context          schema/context/spring-context-2.5.xsdquot;gt;
   lt;context:annotation-config/gt;
The exception is:

Code:
org..beans.factory.BeanCreationException: Error creating bean with name 'contactDao' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org..beans.BeanInstantiationException: Could not instantiate bean class [home.dao.impl.ContactDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org..beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:243)
at org..beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:893)
at org..beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:803)
...
Does anybody know what's wrong here?: I used some bean properties in the bean constructor. Those properties weren't initated yet --gt; the code in the constructor is moved to a @PostConstruct method.

You cannot use @Resource on a constructor... @Autowired you can use on a constructor.

@Resource only works on fields or methods...


Originally Posted by Marten Deinum@Autowired you can use on a constructor.
@Resource only works on fields or methods...

Hey,is this the only difference? What should I use on fields? I'm using @Autowired now, e.g.:Code:
@Service
public class SomeServiceImpl implements SomeService {

@Autowired
private SomeManager someManager;
...
but @Resource seems to work as well. Is there any difference? Additionally, I've read on some blog's, autowireing should be omitted, but why?

Thanks,Kornel
¥
Back Forum Reply New