我是Spring的新用戶。我正在嘗試通過註釋實現依賴注入。我 beans.xml文件是: -依賴注入註釋
<!-- Add your classes base package here -->
<context:component-scan base-package="com.springaction.chapter01"/>
<bean id="greeting" class="com.springaction.chapter01.GreetingImpl">
<property name="greeting">
<value>Naveen Jakad</value>
</property>
</bean>
豆,我要注入的是: -
package com.springaction.chapter01;
import org.springframework.stereotype.Service;
@Service
public class InjectBean {
private int id;
private String name;
public InjectBean() {
super();
}
//setter getter of above instance variables..
}
,並在其中我要注入上述豆的豆是: -
package com.springaction.chapter01;
import org.springframework.beans.factory.annotation.Autowired;
public class GreetingImpl implements Greeting {
private String greeting;
@Autowired
private InjectBean myBean;
public GreetingImpl() {
super();
}
public GreetingImpl(String greeting) {
super();
this.greeting = greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
@Override
public void sayGreeting() {
System.out.println(greeting + " " + myBean);
}
}
所以當我通過測試上述代碼: -
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("config.xml"));
Greeting greeting = (Greeting)beanFactory.getBean("greeting");
greeting.sayGreeting();
我得到輸出「Naveen Jakad null」,意思是簡而言之,我無法實現我的目標。所以,請幫助我,讓我知道我會犯錯