Spring中@Import的三種情況

来源:https://www.cnblogs.com/dongguangming/archive/2020/05/26/12963060.html
-Advertisement-
Play Games

我們在使用Spring框架中,特別是框架級的功能,經常看到有@Import導入功能, ​ 我就介紹下它能導入什麼,首先聲明下@Import是註解,導入類型可分為三類: 1. 導入配置 @Configuration,類似於spring早期版本2.5的import xml文件一樣, <?xml vers ...


 

 

我們在使用Spring框架中,特別是框架級的功能,經常看到有@Import導入功能,


我就介紹下它能導入什麼,首先聲明下@Import是註解,導入類型可分為三類

1.   導入配置 @Configuration,類似於spring早期版本2.5的import 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"  
       xsi:schemaLocation="  
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
       ">  
      
    <import resource="cms-validator-service.xml"/>  
    <import resource="cms-validator-dao.xml"/>  
       
</beans>  

 只是現在註解搶了風頭,但目的一樣,用於使用所有標有@configuration註解的配置。

下麵我就寫個小例子,怎麼建java項目就略了

先建java主包com.spring, 然後分別建子包

com.spring.service,  com.spring.service.impl, com.spring.config, com.spring.test

1.1  建立服務介面

package com.spring.service;

/**
 * 
 * @author dgm
 * @describe "日誌服務介面"
 */
public interface LogService {

    void print(String message);
}

1.2  建立服務實現類,分三種情況,控制台、文件和資料庫mysql

package com.spring.service.impl;

import org.springframework.stereotype.Component;
import com.spring.service.LogService;

/**
 * @author dgm
 * @describe "日誌到控制台"
 */
@Component
public class StdOutLogServiceImpl implements LogService {

	@Override
	public void print(String message) {
        System.out.println(message);
        System.out.println("寫日誌到控制台!");
	}
}


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.springframework.stereotype.Component;
import com.spring.service.LogService;

/**
 * 
 * @author dgm
 * @describe "日誌到文件"
 */
@Component
public class FileLogServiceImpl implements LogService {

	private static final String FILE_NAME="d://LogService.txt";
	@Override
	public void print(String message) {
		try {
			File file = new File(FILE_NAME);
			FileWriter fw = null;
			// true:表示是追加的標誌
			fw = new FileWriter(file, true);
			fw.write(message+"\n");
			fw.close();

	        System.out.println(message);
			System.out.println("寫日誌入文件!");
		} catch (IOException e) {
		}
	}
}


/**
 * @author dgm
 * @describe "寫日誌入mysql資料庫"
 */
@Component
public class MysqlLogServiceImpl implements LogService {

	@Override
	public void print(String message) {
        System.out.println(message);
        System.out.println("寫日誌入資料庫");
	}
}

1.3  寫配置類,三個服務實現類對應三個@Configuration

package com.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.spring.service.LogService;
import com.spring.service.impl.StdOutLogServiceImpl;

@Configuration
public class StdOutConfig {

	@Bean(name="stdOutLogServiceImpl")
	public LogService stdOutLogServiceImpl(){
		return new StdOutLogServiceImpl();
	}
}


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.spring.service.LogService;
import com.spring.service.impl.FileLogServiceImpl;

@Configuration
public class FileLogConfig {

	@Bean(name="fileLogServiceImpl")
	public LogService fileLogServiceImpl(){
		return new FileLogServiceImpl();
	}
}

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.spring.service.LogService;
import com.spring.service.impl.MysqlLogServiceImpl;

@Configuration
public class MysqlLogConfig {

	@Bean(name="mysqlLogServiceImpl")
	public LogService mysqlLogServiceImpl(){
		return new MysqlLogServiceImpl();
	}
}

然後@Import註解登場了

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({StdOutConfig.class, FileLogConfig.class, MysqlLogConfig.class})
public class LogParentConfig {

}

1.4  建立測試類看效果

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.spring.config.LogParentConfig;
import com.spring.service.*;

/**
 * @author dgm
 * @describe "java configuration bean"
 */
public class LogConfigurationAppTest {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext  context = new AnnotationConfigApplicationContext(
				LogParentConfig.class);
		//控制台
		LogService obj = (LogService) context.getBean("stdOutLogServiceImpl");
		System.out.println(obj);
		obj.print("控制台輸出");
		//file
		obj = (LogService) context.getBean("fileLogServiceImpl");
		System.out.println(obj);
		obj.print("文件輸出");
		//mysql
		obj = (LogService) context.getBean("mysqlLogServiceImpl");
		System.out.println(obj);
		obj.print("資料庫mysql");
		
		context.close();
	}
}

輸出效果

 

2.  導入實現ImportSelector介面或子介面DeferredImportSelector的類

@Import annotation can also be configured with an ImportSelector implementation to select @Configuration classes programmatically, based on some selection criteria.

下麵我也演示下,這個很重要,框架里和spring擴展開發用的多,先建立備用子包com.spring.bean和com.spring.importSelector,然後建立配置文件目錄conf

2.1  實現了ImportSelector

2.1.1    建立輔助類ApplicationProperties.java和外置配置文件myapp.properties

package com.spring.bean;

public class ApplicationProperties {
	private String connectionUrl;
	private String connectionName;

	public String getConnectionUrl() {
		return connectionUrl;
	}

	public void setConnectionUrl(String connectionUrl) {
		this.connectionUrl = connectionUrl;
	}

	public String getConnectionName() {
		return connectionName;
	}

	public void setConnectionName(String connectionName) {
		this.connectionName = connectionName;
	}

	@Override
	public String toString() {
		return "ApplicationProperties [connectionUrl=" + connectionUrl
				+ ", connectionName=" + connectionName + "]";
	}
}

然後在conf目錄下建立配置文件myapp.properties,內容如下:

app.url=https://github.com/dongguangming
app.name=dongguangming

2.1.2   建立@Configuration配置類

@Configuration
@PropertySource("classpath:conf/myapp.properties")
public class AppConfig {
	@Autowired
	ConfigurableEnvironment environment;

	@Bean
	ApplicationProperties appProperties() {
		ApplicationProperties bean = new ApplicationProperties();
		bean.setConnectionUrl(environment.getProperty("app.url"));
		bean.setConnectionName(environment.getProperty("app.name"));
		return bean;
	}
}

2.1.3  建立實現了ImportSelector介面的導入類,返回列表裡的值是有標誌@Configuration

public class LogImportSelector implements  ImportSelector{

	@Override
	public String[] selectImports(AnnotationMetadata importingClassMetadata) {
		
		    return new String[]{"com.spring.config.AppConfig","com.spring.config.LogParentConfig"};
	}

}

 2.1.4  建立有@import功能的配置類,導入2.1.3的實現類

package com.spring.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.spring.importSelector.LogImportSelector;

@Configuration
@Import(LogImportSelector.class)
public class LogImportSelectorConfig {

}

2.1.5  編寫測試類

 

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.spring.bean.ApplicationProperties;
import com.spring.config.LogImportSelectorConfig;
import com.spring.service.*;

/**
 * @author dgm
 * @describe "java configuration bean"
 */
public class LogImportSelectorConfigurationAppTest {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
				LogImportSelectorConfig.class);
		// 控制台
		LogService obj = (LogService) context.getBean("stdOutLogServiceImpl");
		System.out.println(obj);
		obj.print("控制台輸出");
		// file
		obj = (LogService) context.getBean("fileLogServiceImpl");
		System.out.println(obj);
		obj.print("文件輸出");
		// mysql
		obj = (LogService) context.getBean("mysqlLogServiceImpl");
		System.out.println(obj);
		obj.print("資料庫mysql");

		//
		ApplicationProperties ap = context.getBean(ApplicationProperties.class);
		System.out.println(ap);

		context.close();
	}
}

 輸出效果:

效果不錯,也能完成bean的註冊

還有一種基於註解的變體,我也示例下,先建個子包com.spring.annotation

建立自定義註解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(LogImportSelector.class)
/**
 * @author dgm
 * @describe "自定義Enable功能"
 */
public @interface EnableLogService {
	//預設日誌輸出到控制台
	String logType() default "stdout";

	@AliasFor("value")
	String[] basePackages() default {};

	@AliasFor("basePackages")
	String[] value() default {}; 
}

然後修改導入選擇器實現類,根據啟用日誌功能時傳的參數絕對載入哪個bean

AnnotationAttributes attributes = AnnotationAttributes
				.fromMap(importingClassMetadata.getAnnotationAttributes(
						EnableLogService.class.getName(), false));
		System.out.println(attributes);

		//根據日誌類型確定載入bean
		String logType = attributes.getString("logType");

		if (logType.equalsIgnoreCase("StdOut")) {
			return new String[] { "com.spring.config.AppConfig",
					"com.spring.config.StdOutConfig" };
		} else if (logType.equalsIgnoreCase("File")) {
			return new String[] { "com.spring.config.AppConfig",
					"com.spring.config.FileLogConfig" };
		} else if (logType.equalsIgnoreCase("Mysql")) {
			return new String[] { "com.spring.config.AppConfig",
					"com.spring.config.MysqlLogConfig" };
		} else {
			return new String[] { "com.spring.config.AppConfig",
					"com.spring.config.LogParentConfig" };
		}

 修改配置類,追加自定義註解@EnableLogService,並設置參數為file(可選stdout,file,mysql)

@Configuration
//@Import(LogImportSelector.class)
@EnableLogService(logType="file")
public class LogImportSelectorConfig {

}

修改測試類,此時不再是三種日誌實現的bean都載入,按配置參數載入

LogService obj = (LogService) context.getBean("fileLogServiceImpl");
		System.out.println(obj);
		obj.print("文件輸出");

 

就因為配置了@EnableLogService(logType="file"),只載入了一個日誌實現bean

 2.2  實現了 DeferredImportSelector

public interface DeferredImportSelector extends ImportSelector {
}

 可是看出它是2.1的子介面

The configuration class directly registered with the application context given preference over imported one. That means a bean of type T, configured in the main configuration will be used instead of a bean of the same type T from imported configuration. That applies to ImportSelector as well. On the other hand, DeferredImportSelector applies after all other configuration beans have been processed.

我們可以比較下實現兩種介面的區別

在主選擇器的配置類LogImportSelectorConfig.java中增加

@Bean
	LogBean logBean() {
		return new LogBean();
	}

	@Bean(name = "fileLogServiceImpl")
	public LogService fileLogServiceImpl() {
		return new FileLogServiceImpl(" 來自LogImportSelectorConfig  ");
	}

 

在文件配置類FileLogConfig.java中修改為

@Bean(name="fileLogServiceImpl")
	public LogService fileLogServiceImpl(){
		return new FileLogServiceImpl("來自  FileLogConfig");
	}

選擇器實現類還是

public class LogImportSelector implements ImportSelector  {。。。}

 執行測試代碼

LogBean bean = context.getBean(LogBean.class);
	    bean.printMessage();

 

此時修改選擇器實現的介面改為DeferredImportSelector,其它不改

public class LogImportSelector implements DeferredImportSelector  {。。。}

 再次執行測試


 

2.3   導入實現了ImportBeanDefinitionRegistrar介面的類

可以先瞄下介面的如何定義和定義了什麼

public interface ImportBeanDefinitionRegistrar {

		   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 迭代器模式是一種使用頻率非常高的設計模式,迭代器用於對一個聚合對象進行遍歷。通過引入迭代器可以將數據的遍歷功能從聚合對象中分離出來,聚合對象只負責存儲數據,聚合對象只負責存儲數據,而遍曆數據由迭代器來完成。 模式動機 一個聚合對象,如一個列表(List)或者一個集合(Set),應該提供一種方法來讓別 ...
  • 代理的本質無論任何時候,只要談到設計模式,大腦中一定要蹦出這四個字“活學活用”。要想對某個事物做到活學活用,必須要對它足夠瞭解,甚至要剖析到本質才行。總是會有些人說,我幹嘛要知道原理,幹嘛要去看源碼?會用就行了。對於這種情況,我只有五個字相送,“你開心就好”。不可否認,認識一個陌生事物,大部分情況還 ...
  • 一、JML初探 ​ 作為一種形式化語言,可以約束 代碼中類和方法的狀態和行為形成規格,通過將一系列具體代碼實現抽象成明確的行為介面,可以形成一種契約式編程模式, 設計者無需考慮實際的數據結構與演算法,可以聚焦於程式的整體邏輯, 形式化語言的無二義性能讓實現者準確理解介面功能,根據問題需要選擇合適的實現 ...
  • 一、基本概念 門面模式(外觀模式)是對象的結構模式,外部與一個子系統的通信必須通過一個統一的門面對象進行。門面模式提供一個高層次的介面,使得子系統更易於使用。 二、通俗解釋 FACADE門面模式:我有一個專業的Nikon相機,我就喜歡自己手動調光圈、快門,這樣照出來的照片才專業,但MM可不懂這些,教 ...
  • 一、基本概念 裝飾模式又名包裝(Wrapper)模式。裝飾模式以對客戶端透明的方式擴展對象的功能,是繼承關係的一個替代方案。 二、通俗解釋 DECORATOR裝飾模式:Mary過完輪到Sarly過生日,還是不要叫她自己挑了,不然這個月伙食費肯定玩完,拿出我去年在華山頂上照的照片,在背面寫上“最好的的 ...
  • 一、基本概念 合成模式屬於對象的結構模式,有時又叫做“部分——整體”模式。合成模式將對象組織到樹結構中,可以用來描述整體與部分的關係。合成模式可以使客戶端將單純元素與複合元素同等看待。 二、通俗解釋 COMPOSITE合成模式:Mary今天過生日。“我過生日,你要送我一件禮物。”“嗯,好吧,去商店, ...
  • 一、基本概念 橋梁模式(Bridge)是對象的結構模式。又稱為柄體(Handle and Body)模式或介面(Interface)模式。橋梁模式的用意是“將抽象化(Abstraction)與實現化(Implementation)脫耦,使得二者可以獨立地變化”。 這句話有三個關鍵詞,也就是抽象化、實 ...
  • 一、基本概念 適配器模式是將某個類的介面轉換成客戶端期望的另一個介面表示,目的是消除由於介面不匹配所造成的的類的相容性問題。 二、通俗解釋 ADAPTER 適配器模式:在朋友聚會上碰到了一個美女Sarah,從香港來的,可我不會說粵語,她不會說普通話,只好求助於我的朋友kent了,他作為我和Sarah ...
一周排行
    -Advertisement-
    Play Games
  • Timer是什麼 Timer 是一種用於創建定期粒度行為的機制。 與標準的 .NET System.Threading.Timer 類相似,Orleans 的 Timer 允許在一段時間後執行特定的操作,或者在特定的時間間隔內重覆執行操作。 它在分散式系統中具有重要作用,特別是在處理需要周期性執行的 ...
  • 前言 相信很多做WPF開發的小伙伴都遇到過表格類的需求,雖然現有的Grid控制項也能實現,但是使用起來的體驗感並不好,比如要實現一個Excel中的表格效果,估計你能想到的第一個方法就是套Border控制項,用這種方法你需要控制每個Border的邊框,並且在一堆Bordr中找到Grid.Row,Grid. ...
  • .NET C#程式啟動閃退,目錄導致的問題 這是第2次踩這個坑了,很小的編程細節,容易忽略,所以寫個博客,分享給大家。 1.第一次坑:是windows 系統把程式運行成服務,找不到配置文件,原因是以服務運行它的工作目錄是在C:\Windows\System32 2.本次坑:WPF桌面程式通過註冊表設 ...
  • 在分散式系統中,數據的持久化是至關重要的一環。 Orleans 7 引入了強大的持久化功能,使得在分散式環境下管理數據變得更加輕鬆和可靠。 本文將介紹什麼是 Orleans 7 的持久化,如何設置它以及相應的代碼示例。 什麼是 Orleans 7 的持久化? Orleans 7 的持久化是指將 Or ...
  • 前言 .NET Feature Management 是一個用於管理應用程式功能的庫,它可以幫助開發人員在應用程式中輕鬆地添加、移除和管理功能。使用 Feature Management,開發人員可以根據不同用戶、環境或其他條件來動態地控制應用程式中的功能。這使得開發人員可以更靈活地管理應用程式的功 ...
  • 在 WPF 應用程式中,拖放操作是實現用戶交互的重要組成部分。通過拖放操作,用戶可以輕鬆地將數據從一個位置移動到另一個位置,或者將控制項從一個容器移動到另一個容器。然而,WPF 中預設的拖放操作可能並不是那麼好用。為瞭解決這個問題,我們可以自定義一個 Panel 來實現更簡單的拖拽操作。 自定義 Pa ...
  • 在實際使用中,由於涉及到不同編程語言之間互相調用,導致C++ 中的OpenCV與C#中的OpenCvSharp 圖像數據在不同編程語言之間難以有效傳遞。在本文中我們將結合OpenCvSharp源碼實現原理,探究兩種數據之間的通信方式。 ...
  • 一、前言 這是一篇搭建許可權管理系統的系列文章。 隨著網路的發展,信息安全對應任何企業來說都越發的重要,而本系列文章將和大家一起一步一步搭建一個全新的許可權管理系統。 說明:由於搭建一個全新的項目過於繁瑣,所有作者將挑選核心代碼和核心思路進行分享。 二、技術選擇 三、開始設計 1、自主搭建vue前端和. ...
  • Csharper中的表達式樹 這節課來瞭解一下表示式樹是什麼? 在C#中,表達式樹是一種數據結構,它可以表示一些代碼塊,如Lambda表達式或查詢表達式。表達式樹使你能夠查看和操作數據,就像你可以查看和操作代碼一樣。它們通常用於創建動態查詢和解析表達式。 一、認識表達式樹 為什麼要這樣說?它和委托有 ...
  • 在使用Django等框架來操作MySQL時,實際上底層還是通過Python來操作的,首先需要安裝一個驅動程式,在Python3中,驅動程式有多種選擇,比如有pymysql以及mysqlclient等。使用pip命令安裝mysqlclient失敗應如何解決? 安裝的python版本說明 機器同時安裝了 ...