SpringFramework Autowiredを設定したプロパティがNullになる問題
はじめに
Spring Framework ではAutowiredアノテーションを利用してクラスのインジェクションができるが、
ServiceクラスでAutowiredを設定したプロパティがNullになってしまう事象が発生した。
実現したかったこと
PropertiesFactoryBeanを利用して、Propertiesファイルを読み込み、プロパティを利用したいクラスで Autowiredを利用してプロパティインスタンスを読み込む。
<bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:application.properties</value> </list> </property> </bean>
AutowiredしたプロパティがNull
Serviceクラスで以下のようにapplicationPropertiesをAutowiredしたが、Null。
@Service public class SalesService { static Logger log = Logger.getLogger(SalesService.class); @Autowired private Properties applicationProperties; → Null ... }
原因
Autowiredを利用するには、サービスを呼び出すコントローラクラスでもAutowiredを利用して、サービスクラスをDIしておく必要があった。
- 失敗(Nullになる) サービスクラスをnewして利用すると、サービスクラスのAutowiredが有効にならない。
@Controller public class SalesController { ... /** * 売上レポート 画面表示 * @return */ @RequestMapping(value = "/sales/report", method = GET) public Object reportView(Model model) throws ApplicationException, IllegalAccessException, NoSuchMethodException, IOException { SalesService salesService = new SalesService(); return "sales/report"; } }
- 成功 コントローラクラスで、サービスクラスをAutowiredでDIしておく。
@Controller public class SalesController { @Autowired private SalesService salesService; ... }
@Service public class SalesService { @Autowired private Properties applicationProperties; → Nullにならずにインスタンス化されている ... }