Springコンポーネントスキャンが機能していないようです。Spring3.1とtomcat7.0を使用しています。
これは私のapplicationContext.xmlがどのように見えるかです:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.abc"/>
<bean id="myBean" class="com.efg.test.MyBean" />
</beans>
私はこのようなクラスを持っています:
package com.abc.test
@Component
class Test {
@Autowired
private static MyBean myBean;
public static MyBean getMyBean() { return myBean; }
public static void setMyBean(MyBean bean) { myBean = bean; }
}
TestはWebアプリケーションの起動時にSpringによって初期化され、myBeanが自動的に挿入されることを期待していたので、Testの(静的)メソッドを呼び出すと、myBeanへのnull以外の参照があります。
ただし、myBeanは注入されず、常にnullになります(myBean自体はシングルトンとして初期化され、注入されないだけです)。これを機能させるには、他に何をする必要がありますか?TestクラスをapplicationContext.xmlに追加すると、すべてが機能します。私の推測では、TestはSpringによって初期化されていないため、有線ではありません。
更新: 静的コンテキスト(このクラスのメソッドはJSP関数と呼ばれます)からautowiredフィールドにアクセスできる必要があるため、静的である必要があります。