注意:这是针对常见问题的规范答案.
我有一个Spring @Serviceclass(MileageFeeCalculator),它有一个@Autowiredfield(rateService),但该字段是null我尝试使用它时.日志显示正在创建MileageFeeCalculatorbean和MileageRateServicebean,但NullPointerException每当我尝试mileageCharge在我的服务bean上调用该方法时,我都会得到.为什么Spring没有自动装配领域?
控制器类:
@Controller
public class MileageFeeController {
@RequestMapping("/mileage/{miles}")
@ResponseBody
public float mileageFee(@PathVariable int miles) {
MileageFeeCalculator calc = new MileageFeeCalculator();
return calc.mileageCharge(miles);
}
}
Run Code Online (Sandbox Code Playgroud)
服务类:
@Service
public class MileageFeeCalculator {
@Autowired
private MileageRateService rateService; // <--- should be autowired, is null
public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile()); // <--- throws NPE
}
}
Run Code Online (Sandbox Code Playgroud)
应该自动装配的服务bean,MileageFeeCalculator但它不是:
@Service …Run Code Online (Sandbox Code Playgroud) 我有一堆Spring bean,它们是通过注释从类路径中获取的,例如
@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {
// Implementation omitted
}
Run Code Online (Sandbox Code Playgroud)
在Spring XML文件中,定义了一个PropertyPlaceholderConfigurer:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/app.properties" />
</bean>
Run Code Online (Sandbox Code Playgroud)
我想将app.properites中的一个属性注入上面显示的bean中.我不能简单地做一些事情
<bean class="com.example.PersonDaoImpl">
<property name="maxResults" value="${results.max}"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
因为PersonDaoImpl在Spring XML文件中没有特征(它是通过注释从类路径中获取的).我有以下几点:
@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {
@Resource(name = "propertyConfigurer")
protected void setProperties(PropertyPlaceholderConfigurer ppc) {
// Now how do I access results.max?
}
}
Run Code Online (Sandbox Code Playgroud)
但是我不清楚我如何访问我感兴趣的房产ppc?