DIコンテナを使わずにSpringでBeanを手動で注入する方法

Springでは、Beanを手動で注入するには、以下の方法があります。

  1. Javaの設定クラス(@Configuration)を活用する:インジェクションしたいBeanを返す@Beanアノテーション付きメソッドを作成します。それを利用したいクラス側では、@Autowiredまたは@Injectアノテーションを使用して、このメソッドが返すBeanをインポートします。
@Configuration
public class AppConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

@Service
public class MyService {
    @Autowired
    private MyBean myBean;
}
  1. XML設定ファイルを使用:注入する必要のあるBeanをXML設定ファイルで定義し、他のBeanからref属性を利用して参照する。
<bean id="myBean" class="com.example.MyBean" />
<bean id="myService" class="com.example.MyService">
    <property name="myBean" ref="myBean" />
</bean>
  1. @Componentあるいは@Serviceアノテーションを使用:手動でインジェクトする必要があるBeanに@Componentあるいは@Serviceを付け、ほかのBeanから@Autowiredあるいは@Injectを使って参照します。
@Component
public class MyBean {
    // ...
}

@Service
public class MyService {
    @Autowired
    private MyBean myBean;
}
  1. @Autowiredや@Injectアノテーションを使用:他のBean内で直接@Autowiredや@Injectアノテーションを使用して手動で注入するBeanを参照します。
@Service
public class MyService {
    @Autowired
    private MyBean myBean;
}

どの方法を使用したとしても、Spring は起動時に Bean の注入を自動的にスキャンして処理します。

bannerAds