IoC容器(1):IoC容器、BeanFactory、ApplicationContext


1.制御ユニット(IoC)、IoC容器


「独立制御」(Inversion of Control)は、「依存注入」(Dependency Injection)とも呼ばれます.
使用する依存オブジェクトを直接作成するのではなく、注入して使用する方法です.
スプリングIoCコンテナの主な機能は、「空の作成、編み込み、空の提供」(空の作成、空の注入の依存性、空のスキャンの管理)です.

2. BeanFactory


スプリングIoC容器最上階のインターフェースはBeanFactoryです.Spring公式ドキュメントでは、BeanFactoryの要点を次のように定義します.
「この方法のポイントは、バックアップ・ファクトリがアプリケーション・コンポーネントの中央レジストリであり、アプリケーション・コンポーネントの構成を集中させることです(たとえば、個々のオブジェクトがプロパティ・ファイルを読み込む必要がなくなりました).
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html
つまり、要約すると次のような役割があります.
  • アプリケーションコンポーネントの中央リポジトリ.
  • 空の構成ソースから空の定義を取得し、空を構築して提供します.
  • ではビンは何ですか.
  • スプリングIoCコンテナによって管理されるオブジェクト.
  • また、登録空の理由は以下の通りです.
  • 依存性管理:依存性管理と注入のためにSpringIoCコンテナに空に登録する必要があります.
  • 空のスキャン管理:
    -シングルトーン(default):オブジェクトを繰り返し使用するため、特にデータベースまたはリポジトリオブジェクトをシングルトーンとして作成するには、メモリまたは実行時のパフォーマンスが向上します.
    -プロトタイプ:各異なるオブジェクト
  • ライフサイクルインタフェースをサポートする:空の作成時に他の操作を実行するか、スプリング自体でライフサイクルコールバックを使用して追加機能
  • を作成する.
    ライフサイクルインタフェースの例
    
    @Service
    public class BookService {
    
        private BookRepository myBookRepository;
    
        public BookService(BookRepository bookRepository){
            this.bookRepository = bookRepository;
        }
        
        public Book save(Book book) {
            book.setCreated(new Date());
            book.setBookstatus(BookStatus.DRAFT);
            return bookRepository.save(book);
        }
    
        @PostConstruct
        public void postConstruct(){
            System.out.println("=================");
            System.out.println("Hello");
        }
    }
    空の工場ライフサイクル
    https://velog.io/@jsj3282/IoC-%EC%BB%A8%ED%85%8C%EC%9D%B4%EB%84%88%EC%99%80-ApplicationContext-BeanFactory

    3. ApplicationContext


    ApplicationContextはBenFactoryを継承しており、BenFactoryとして機能したり、他の機能を提供したりすることができます.
    ( https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContext.html )
    以下はSpring公式ドキュメントのApplicationContextが提供する機能です.
  • アプリケーションコンポーネントにアクセスするためのbeanファクトリメソッド
  • は、ファイルリソース
  • の通常のロードをサポートする.
  • 登録されたリスナーにイベントを発行するための機能
  • .
  • メッセージを分析して国際化
  • をサポートする
  • 親コンテキストから
  • を継承

    4.アプリケーションコンテキストと各種設定の空の方法



    スプリングIoCコンテナの役割
  • 空のインスタンス
  • を作成します.
  • 依存関係を確立
  • アイドル
  • 空の設定ファイル
  • 空リスト
  • ビンの定義が含まれています.
    -名前
    -クラス
    -スキャン
    -ジェネレータ仕様(constructor)
    -コンフィギュレータ
  • 空の設定ファイルを作成するには:
    1. ClassPathXmlApplicationContext (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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
        <bean id="bookService" class="com.example.springtest.BookService" scope="singleton" autowire="default">
            <property name="bookRespository" ref="bookRepository"></property>
        </bean>
        <bean id="bookRepository" class="com.example.springtest.BookRespository" scope="singleton" autowire="default"></bean>
    </beans>
    @SpringBootApplication
    public class SpringtestApplication {
    
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            String[] beanDefinitionNames = context.getBeanDefinitionNames();
            System.out.println(Arrays.toString(beanDefinitionNames));
            BookService bookService = (BookService) context.getBean("bookService");
            System.out.println(bookService.bookRespository != null);
        }
    }
    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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="com.example.springtest"></context:component-scan>
    </beans>
    次に、で作成したパッケージのサブクラスで、@Componentメタ宣言の別名(ex@Service)を持つクラスファイルをスキャンして空に登録します.また、依存性注入には@Autowiredという注釈が使用されます.
    //@Component
    @Service
    public class BookService {
    
        @Autowired
        BookRespository bookRespository;
    
        public void setBookRespository(BookRespository bookRespository){
            this.bookRespository = bookRespository;
        }
    }
    @SpringBootApplication
    public class SpringtestApplication {
    
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            String[] beanDefinitionNames = context.getBeanDefinitionNames();
            System.out.println(Arrays.toString(beanDefinitionNames));
            BookService bookService = (BookService) context.getBean("bookService");
            System.out.println(bookService.bookRespository != null);
        }
    }
  • AnnotationConfigApplicationContext (Java)
  • @Configuration
    public class ApplicationConfig {
        
        @Bean
        public BookRespository bookRepository(){
            return new BookRespository();
        }
        
        @Bean
        public BookService bookService(){
            BookService bookService = new BookService();
            bookService.setBookRespository(bookRepository());
            return bookService;
        }
    }
    または
    @Configuration
    public class ApplicationConfig {
       
        @Bean
        public BookRespository bookRepository(){
            return new BookRespository();
        }
        @Bean
        public BookService bookService(BookRespository bookRespository){
            BookService bookService = new BookService();
            bookService.setBookRespository(bookRespository);
            return bookService;
        }
        
    }
    @SpringBootApplication
    public class SpringtestApplication {
    
        public static void main(String[] args) {
            ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
            String[] beanDefinitionNames = context.getBeanDefinitionNames();
            System.out.println(Arrays.toString(beanDefinitionNames));
            BookService bookService = (BookService) context.getBean("bookService");
            System.out.println(bookService.bookRespository != null);
    
        }
    }
    ではjavaプロファイルでは、毎日空の登録が必要ですか?
    そうする必要はありません.@ComponentScanのプレゼンテーションを使うだけです.
    スイープエレメント
  • の設定方法
    -XML設定でコンテキスト:component-scan
    -Javaプロファイルで@ComponentScan
  • @Component Anotationを使用するすべてのクラスが自動的に空に登録されます.
  • @ComponentScan(basePackages = "com.example.springtest")
    @Configuration
    public class ApplicationConfig {
    
    }
    上記basepackagesを用いて、パッケージからパッケージへのサブパッケージを素子スキャンした.または、basepackageではなくbasepackageClassesを使用することもできます.basePackageClassesを使用すると、指定したクラスの場所から構成部品のスキャンを開始できます.同様に,@Componentメタ解析のコメントを持つクラスをスキャンする.
    @Configuration
    @ComponentScan(basePackageClasses = SpringtestApplication.class)
    public class ApplicationConfig {
    }
    
    //@Component
    @Service
    public class BookService {
    
        @Autowired
        BookRespository bookRespository;
    
        public void setBookRespository(BookRespository bookRespository){
            this.bookRespository = bookRespository;
        }
    }
    @Repository
    public class BookRespository {
    }
    もちろんspringBootを使用すると、springBootは空のプロファイルを直接作成するのではなく、アプリケーションコンテキストを作成します.
    @SpringBootApplication
    public class SpringtestApplication {
    
        public static void main(String[] args) {
    
        }
    }
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @SpringBootConfiguration
    @EnableAutoConfiguration
    @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
    public @interface SpringBootApplication {
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Configuration
    @Indexed
    public @interface SpringBootConfiguration {
    したがって、これ自体が空のプロファイルです.
    リファレンス
  • インフラストラクチャ:スプリングフレームキーテクノロジー(白旗線)