私はクラスを持っています:
public class Base
{
private MyExecutor executor;
}
new 演算子を使用してクラス Base の新しいインスタンスを作成し、Spring によって注入された MyExecutor の同じシングルトン インスタンスを使用するにはどうすればよいですか?? 提案してください。
executor を非プロトタイプとして宣言します (つまり、シングルトンがデフォルトであるため、プロトタイプにしないでください)。ApplicationContext から Bean を取得し、それを のコンストラクターに渡しBase
ます。
MyExecutor
別のオプションは、Spring によって呼び出されるコンストラクターからの静的フィールドとしてシングルトン インスタンスを格納することです。次に、getInstance
静的メソッドを提供します。
これは、Spring がデフォルトで行うことであり、Bean の同じインスタンスを注入します。たとえば、以下の B1 と B2 は、MyExecutor Bean のスコープをsingleton
toprototype
または other に変更しない限り、単純にデフォルトで MyExecutor Bean の同じインスタンスを取得します。
public class B1 {
@Autowired
private MyExecutor executor;
...
public class B2 {
@Autowired
private MyExecutor executor;
...
あなたはこれを行うことができます:
ApplicationContext ctx = ...
YourClass someBeanNotCreatedBySpring = ...
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(
someBeanNotCreatedBySpring,
AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true);
@Autowired
YourClass 内で etc を使用して、注入するフィールドなどを指定できます。
または、次の注釈を Base に追加@Autowired
して、注入するフィールドを指定することもできます
@Configurable(preConstruction=true,dependencyCheck=true,autowire=Autowire.BY_TYPE)
@EnableSpringConfigured
そしてXMl構成で以下
<context:load-time-weaver weaver-class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver" aspectj-weaving="on"/>
また
<context:load-time-weaver aspectj-weaving="autodetect"/>
重要な概念は、有効にすることですLoad time weaving