オートスキャンのスプリングフィルタコンポーネント

自動スキャンのSpring Filterコンポーネント

このSpring auto component scanning tutorialでは、Springにコンポーネントを自動スキャンさせる方法について学習します。 この記事では、自動スキャンプロセスでコンポーネントフィルタを実行する方法を示します。

1. フィルターコンポーネント-含める

次の例を参照して、Springの「filtering」を使用して、定義された「正規表現」に一致するコンポーネントの名前をスキャンして登録します。クラスには@Componentアノテーションが付いていません。

DAO層

package com.example.customer.dao;

public class CustomerDAO
{
    @Override
    public String toString() {
        return "Hello , This is CustomerDAO";
    }
}

サービス層

package com.example.customer.services;

import org.springframework.beans.factory.annotation.Autowired;
import com.example.customer.dao.CustomerDAO;

public class CustomerService
{
    @Autowired
    CustomerDAO customerDAO;

    @Override
    public String toString() {
        return "CustomerService [customerDAO=" + customerDAO + "]";
    }

}

春のフィルタリング。



    

        

        

    

それを実行します

package com.example.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.customer.services.CustomerService;

public class App
{
    public static void main( String[] args )
    {
        ApplicationContext context =
        new ClassPathXmlApplicationContext(new String[] {"Spring-AutoScan.xml"});

        CustomerService cust = (CustomerService)context.getBean("customerService");
        System.out.println(cust);

    }
}

出力

CustomerService [customerDAO=Hello , This is CustomerDAO]

このXMLフィルタリングでは、すべてのファイルの名前にDAOまたはサービス(DAO.Services.)が含まれています。単語が検出され、Springコンテナに登録されます。

2. フィルターコンポーネント-除外

一方、指定したコンポーネントを除外して、SpringがSpringコンテナに検出して登録するのを防ぐこともできます。

@Serviceアノテーションが付けられたファイルを除外します。

    
        
    

DAOワードを含むファイル名を除外します。

    
        
    

ソースコードをダウンロード