1. 程式人生 > >spring註解開發——容器部分

spring註解開發——容器部分

  • 給容器註冊元件@Configuration、@Bean
    1. 首先我們先生成一個maven專案
    2. 在pom檔案中引入spring的核心元件context依賴:
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>4.3.20.RELEASE</version>
          </dependency>
      
      咱們也引入一下junit測試依賴,方便測試使用
      <
      dependency
      >
      <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.0</version> <scope>test</scope> </dependency>
    3. 首先建立一個實體類Person
      如程式碼所示:
      public class Person {
      private String name;
      private int age;
      public String getName() {
      return name;
      } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { super(); this.name = name; this.age = age; } public Person() { super(); } @Override public String toString() { return "Person [name="
      + name + ", age=" + age + "]"; } }
    4. 首先我們先使用xml配置的方式來配置bean,並從容器中獲取實體
      在resource資料夾下建立beans.xml的spring配置檔案:
      <?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="entity.Person">
      <property name="name" value="張三"></property>
      <property name="age" value="10"></property>
      </bean>
      </beans>
      
      然後在測試類中獲取實體:
      	@Test
      		public void testOne() {
      		System.out.println("讀取xml配置方法");
      		//通過ClassPathXmlApplicationContext類讀取對應的配置檔案,得到spring容器ApplicationContext
      		ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
      		//從spring容器中獲取裝配的bean元件
      		Person person = (Person) app.getBean("person");
      		System.out.println(person.toString());
      		}
      
      執行結果為:
      讀取xml配置方法
      十一月 24, 2018 10:03:05 
      org.springframework.context.support.ClassPathXmlApplicationContextprepareRefresh
      資訊: Refreshing org[email protected]7506e922: startup date [Sat Nov 24 22:03:05 CST 2018]; root of context hierarchy
      十一月 24, 2018 10:03:05 下
      org.springframework.beans.factory.xml.XmlBeanDefinitionReaderloadBeanDefinitions
      資訊: Loading XML bean definitions from class path resource [beans.xml]
      Person [name=張三, age=10]
      
    5. 接下在咱們通過spring的@Configuration和@Bean註解來實現以上內容:
      建立BeanConfig類:
      //讓spring識別此類為配置類
      @Configuration
      public class BeanConfig {
      //此註解為配置元件,預設id為方法名
      @Bean
      public Person person() {
      	return new Person("李四",20);
      	}
      }
      
      測試類進行測試:
      	@Test
      	public void testTwo() {
      	System.out.println("通過註解配置方法");
      	//通過AnnotationConfigApplicationContext類獲取配置類
      	ApplicationContext app = new AnnotationConfigApplicationContext(BeanConfig.class);
      	//從容器中獲取元件
      	Person person = (Person) app.getBean("person");
      	System.out.println(person.toString());
      	}
      
      執行結果:
      通過註解配置方法
      十一月 24, 2018 10:03:05 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
      資訊: Refreshing org.spring[email protected]20322d26: startup date [Sat Nov 24 22:03:05 CST 2018]; root of context hierarchy
      Person [name=李四, age=20]
      
    6. 通過這兩種方式可以發現,註解方式原理跟xml配置一致,都是講元件載入到spring容器中讓其識別。
  • 按照條件註冊bean元件[email protected]
    1. spring底層給我們提供可以根據條件來裝配元件。大致原理是通過實現springframework.context.annotation.Condition介面來自己編寫裝配條件類。然後通過spring註解@Conditional({xxxxxx.class})來實現按照條件註冊元件。
    2. 下面通過裝配person來體驗一下:通過驗證伺服器系統來作為條件來進行裝配bean
      先定義一個linux的條件類:
      import org.springframework.context.annotation.Condition;
      import org.springframework.context.annotation.ConditionContext;
      import org.springframework.core.env.Environment;
      import org.springframework.core.type.AnnotatedTypeMetadata;
      public class LinuxCondition implements Condition{
      public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
      Environment env =  context.getEnvironment();
      String name = env.getProperty("os.name");
      if(name.contains("Linux")) {
      		return true;
      	}
        	    return false;
          }
      }
      
      再定義一個window的條件類:
      public class WindowCondition implements Condition{
      public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
      	//獲取環境資訊
      	Environment env  = context.getEnvironment();
      	String name = env.getProperty("os.name");
      	//獲取容器中裝配的bean資訊
      	BeanDefinitionRegistry beans =  context.getRegistry();
      	//判斷是否為windows系統以及是否裝配了person元件類
      	if(name.contains("Windows")&&beans.containsBeanDefinition("person")) {
           	return true;
           	}
           	return false;
          }
      }
      
      然後配置bean:
      @Configuration
      public class BeanConfig {
      	@Bean("person")
      	public Person person() {
      	return new Person("李四",20);
      	}
      	//只有在windows系統下以及容器中有person元件的情況下才會裝配
      	@Conditional({WindowCondition.class})
      	@Bean("window")
      	public Person personWin() {
      	return new Person("window",100);
      	}
      	//只有在linux系統下才會被裝配
      	@Conditional({LinuxCondition.class})
      	@Bean("linux")
      	public Person personLin() {
      	return new Person("linux",200);
      	}
        }
      
      測試類:
      @Test
      public void testThree() {
      ApplicationContext app = new AnnotationConfigApplicationContext(BeanConfig.class);
      //獲取容器中所有型別為Person的元件的名稱
      String[] names  = app.getBeanNamesForType(Person.class);
      for (String string : names) {
      	System.out.println(string);
      	}
      }
      
      測試結果為:
      十一月 25, 2018 11:52:25 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
      資訊: Refreshing org.spring[email protected]512ddf17: startup date [Sun Nov 25 11:52:25 CST 2018]; root of context hierarchy
      person
      window
      
    3. 條件裝配在springboot底層實現自動裝配時大量使用。先了解一下這個註解,以後方便了解springboot自動裝配方式。