Spring註冊bean的兩種形式——基於XML文件和基於註解

環境準備

創建一個Maven項目,然後在pom.xml中添加spring-context包:

  <dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-context</artifactId>
		    <version>4.3.26.RELEASE</version>
		</dependency>
  </dependencies>

spring-context包是Spring IoC容器的基礎,並依賴了以下幾個包:
在這裏插入圖片描述

bean

含義:
在 Spring 中,構成應用程序主幹的對象和由 Spring IoC 容器管理的對象稱爲 bean。 bean 是由 Spring IoC 容器實例化、組裝和管理的對象。 否則,bean 只是應用程序中的許多對象之一。

屬性:

  • id 屬性是用於標識單個 bean 定義的字符串。 即爲bean的名稱。如果沒有定義則會
  • name 屬性也可以定義 bean 的名稱,並且可以與id屬性同時使用,能以逗號或空格隔開起多個別名。
  • class 屬性定義 bean 的類型並且要使用類的全限定名。
  • peoperty屬性是定義類的屬性,其中的 name 屬性定義的是屬性的名稱,而 value 是它的值。

一、傳統的XML方式註冊

1.首先創建一個實體類Person,如下:

package com.learn.bean;
public class Person {
	private int id;
	private String name;	
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + "]";
	}
	public Person(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
		public Person() {
	}
	//Getters and Setters
}

這裏需要注意的是由於javaBean的規範,在沒有申明構造函數時,java將自動創建構造函數。但是若已申明帶參數構造函數,必須申明無參數構造函數,否則當你Spring註冊Bean時調用無參數構造函數,將會編譯錯誤。

2.創建一個applicationContext.xml用於配置Bean,如下:

<?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.xsd">
    
    <bean id="person" class="com.learn.bean.Person">
        <property name="id" value="1"></property>
        <property name="name" value="xiaomin"></property>
    </bean>           
 </beans>

這樣就成功將person注入到Spring容器中。

這裏需要注意的是:id或name屬性不是必須的,當id和name屬性沒有聲明時, Spring 將會採用 “全限定名#{number}” 的格式生成編號。全限定名即爲定義的class屬性值。 例如這裏,如果沒有聲明 “id=“person”” 的話,那麼 Spring 爲其生成的id就是 “com.learn.bean.Person#0”,當它第二次聲明沒有 id 屬性的 同類型bean 時,id就是 “com.learn.bean.Person#1”,以此類推。

刪除上面bean配置的id,此時查看Spring IoC容器中的所有的id:

public class XmlTest {
	public static void main(String[] args) {
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
		//獲取Ioc容器中所有Bean的id
       String[] names= applicationContext.getBeanDefinitionNames();	
       for(String i:names) {
    	   System.out.println(i);
       }		
	}
}

在這裏插入圖片描述

二、註解方式註冊

1.@Configuration註解+@Bean註解的方式

@Configuration註解:
從Spring3.0,@Configuration用於定義配置類,可替換xml配置文件,被註解的類內部包含有一個或多個被@Bean註解的方法,這些方法將會被AnnotationConfigApplicationContextAnnotationConfigWebApplicationContext類進行掃描,並用於構建bean定義,初始化Spring容器。

注意:@Configuration註解的配置類有如下要求:

  • @Configuration不可以是final類型;
  • @Configuration不可以是匿名類;
  • 嵌套的configuration必須是靜態類。

@Bean註解:

  1. @Bean註解在返回實例的方法上,如果未通過@Bean指定bean的名稱,則默認與標註的方法名相同。
  2. 可以使用屬性value或name指定bean的多個名稱。如:@Bean(value = {"a","b","c"})
  3. @Bean註解默認作用域爲單例singleton作用域,可通過@Scope(“prototype”)設置爲原型作用域。

下面來用這兩個註解來註冊bean:

1.創建一個類名爲SpringConfig,@Configuration標註在類上,相當於把該類作爲spring的xml配置文件中的,作用爲配置spring容器(應用上下文)。
2.@Bean標註在方法上(返回某個實例的方法),等價於spring的xml配置文件中的,作用爲註冊bean對象。如下:

@Configuration
public class SpringConfig {
	@Bean
	public Person person() {
		return new Person(1,"張三");
	}
}

3.創建測試類,這裏使用 AnnotationConfigApplicationContext 類去初始化 Spring IoC 容器。參數是 StudentConfig 類,這樣 Spring IoC 就會根據註解的配置去解析對應的資源,來生成 IoC 容器了。

public class AnnotationTest {
	public static void main(String[] args) {	
		//獲取Spring的IOC容器
		ApplicationContext applicationContext=new AnnotationConfigApplicationContext(SpringConfig.class);
		//從容器中獲取bean
		Person person=(Person) applicationContext.getBean("person");
		System.out.println(person);
	}
}

4.查看輸出:
在這裏插入圖片描述

2.@Compoent 註解+@ComponentScan註解方式

@Compoent 註解:
表示 Spring IoC 會把這個類掃描成一個 bean 實例,而其中的 value 屬性代表這個類在 Spring 中的 id,這就相當於在 XML 中定義的 Bean 的 id:,也可以簡寫成 @Component(“student1”)或@Component ,對於不寫的,Spring IoC 容器就默認以類名來命名作爲 id,只不過首字母小寫,配置到容器中。

@ComponentScan註解:
代表進行掃描,默認是掃描當前包的路徑中帶有或間接使用了 @Component 、@Service、@Controller、@Repository註解的類。
它有兩個配置項用來指定掃描的包和類:

  • basePackages:它可以配置一個 Java 包的數組,Spring 會根據它的配置掃描對應的包和子包,將配置好的 Bean 裝配進來
  • basePackageClasses:它可以配置多個類。這個較少使用。

使用這兩個註解,Spring 會根據@ComponentScan註解爲包和子包進行掃描裝配對應配置的 Bean。

下面來驗證這兩個註解:

1.在Person類上加上@Compoent 註解

@Component
public class Person {
	private int id;
	private String name;
	...省略

2.SpringConfig類中只加上@ComponentScan(basePackages = "com.learn"),這裏等價於xml配置中的<context:component-scan base-package="com.learn"/>

@ComponentScan(basePackages = "com.learn")
public class SpringConfig {
//	@Bean(value = {"a","b","c"})
//	public Person person() {
//		return new Person(1,"張三");
//	}
}

3.結果可以看到配置成功,可以取到person這個bean:
在這裏插入圖片描述

參考:
https://www.cnblogs.com/duanxz/p/7493276.html
https://www.cnblogs.com/wmyskxz/p/8830632.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章