Spring經常使用配置

概述

  本文主要講解Spring的一些經常使用配置,使用Java Bean來配置。java

  須要注意的均寫在註釋裏面了。web


 

配置Bean的Scope

 1 package com.wisely.highlight_spring4.ch2.scope;
 2 
 3 import org.springframework.context.annotation.Scope;
 4 import org.springframework.stereotype.Service;
 5 
 6 /**
 7  * 編寫Prototype的bean
 8  */
 9 @Service
10 @Scope("prototype")//聲明scope爲prototype,每次調用新建一個bean的實例
11 //@Scope("singleton")//一個spring容器中只有一個bean的實例,是spring的默認配置,全容器共享一個實例
12 //@Scope("request")//web項目中,給每個http request新建一個bean的實例
13 //@Scope("session")//web項目中,給每個http session新建一個bean實例
14 //@Scope("globalSession")//只在portal應用中有用,給每個global http session新建一個bean實例
15 public class DemoPrototypeService {
16 
17 }
編寫Prototype的bean
 1 package com.wisely.highlight_spring4.ch2.scope;
 2 
 3 import org.springframework.stereotype.Service;
 4 
 5 /**
 6  * 編寫Singleton的bean
 7  */
 8 @Service //默認爲Singleton,至關於@Scope("singleton")
 9 public class DemoSingletonService {
10 
11 }
編寫Singleton的bean
 1 package com.wisely.highlight_spring4.ch2.scope;
 2 
 3 import org.springframework.context.annotation.ComponentScan;
 4 import org.springframework.context.annotation.Configuration;
 5 
 6 /**
 7  * 配置類
 8  */
 9 @Configuration
10 @ComponentScan("com.wisely.highlight_spring4.ch2.scope")
11 public class ScopeConfig {
12 
13 }
配置類
 1 package com.wisely.highlight_spring4.ch2.scope;
 2 
 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4 
 5 public class Main {
 6     public static void main(String[] args) {
 7         AnnotationConfigApplicationContext context =
 8                 new AnnotationConfigApplicationContext(ScopeConfig.class); 
 9         DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
10         DemoSingletonService s2 = context.getBean(DemoSingletonService.class);
11         DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
12         DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);
13         System.out.println("s1與s2是否相等:"+s1.equals(s2));
14         System.out.println("p1與p2是否相等:"+p1.equals(p2));
15         context.close();
16     }
17 }
運行

Spring EL和資源調用配置

 1 package com.wisely.highlight_spring4.ch2.el;
 2 
 3 import org.springframework.beans.factory.annotation.Value;
 4 import org.springframework.stereotype.Service;
 5 
 6 /**
 7  * 需被注入的類
 8  */
 9 @Service
10 public class DemoService {
11     //注入普通字符串
12     @Value("其餘類的屬性")
13     private String another;
14 
15     public String getAnother() {
16         return another;
17     }
18 
19     public void setAnother(String another) {
20         this.another = another;
21     }
22     
23 }
需被注入的類
 1 package com.wisely.highlight_spring4.ch2.el;
 2 
 3 import org.apache.commons.io.IOUtils;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.beans.factory.annotation.Value;
 6 import org.springframework.context.annotation.Bean;
 7 import org.springframework.context.annotation.ComponentScan;
 8 import org.springframework.context.annotation.Configuration;
 9 import org.springframework.context.annotation.PropertySource;
10 import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
11 import org.springframework.core.env.Environment;
12 import org.springframework.core.io.Resource;
13 
14 /**
15  * 配置類
16  */
17 @Configuration
18 @ComponentScan("com.wisely.highlight_spring4.ch2.el")
19 //指定配置文件地址
20 @PropertySource("classpath:com/wisely/highlight_spring4/ch2/el/test.properties")
21 public class ElConfig {
22     //注入普通字符串
23     @Value("I Love You!")
24     private String normal;
25     //注入操做系統屬性
26     @Value("#{systemProperties['os.name']}")
27     private String osName;
28     //注入表達式結果
29     @Value("#{ T(java.lang.Math).random() * 100.0 }")
30     private double randomNumber;
31     //注入其餘bean屬性
32     @Value("#{demoService.another}")
33     private String fromAnother;
34     //注入文件資源
35     @Value("classpath:com/wisely/highlight_spring4/ch2/el/test.txt")
36     private Resource testFile;
37     //注入網址資源
38     @Value("http://www.baidu.com")
39     private Resource testUrl;
40     //注入配置文件
41     @Value("${book.name}")
42     private String bookName;
43     @Autowired
44     private Environment environment;
45     /**
46      * 若是使用@Value注入配置文件,則要配置一個PropertySourcesPlaceholderConfigurer
47      */
48     @Bean
49     public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
50         return new PropertySourcesPlaceholderConfigurer();
51     }
52 
53     public void outputResource() {
54         try {
55             System.out.println(normal);
56             System.out.println(osName);
57             System.out.println(randomNumber);
58             System.out.println(fromAnother);
59             System.out.println(IOUtils.toString(testFile.getInputStream()));
60             System.out.println(IOUtils.toString(testUrl.getInputStream()));
61             System.out.println(bookName);
62             System.out.println(environment.getProperty("book.author"));
63         } catch (Exception e) {
64             e.printStackTrace();
65         }
66     }
67 }
配置類
 1 package com.wisely.highlight_spring4.ch2.el;
 2 
 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4 
 5 public class Main {
 6     
 7     public static void main(String[] args) {
 8          AnnotationConfigApplicationContext context =
 9                     new AnnotationConfigApplicationContext(ElConfig.class);
10          
11          ElConfig resourceService = context.getBean(ElConfig.class);
12          
13          resourceService.outputResource();
14          
15          context.close();
16     }
17 
18 }
運行

 

Bean的初始化和銷燬

 1 package com.wisely.highlight_spring4.ch2.prepost;
 2 
 3 /**
 4  * 使用@Bean形式的Bean
 5  */
 6 public class BeanWayService {
 7     public void init() {
 8         System.out.println("@Bean-init-method");
 9     }
10 
11     public BeanWayService() {
12         super();
13         System.out.println("初始化構造函數-BeanWayService");
14     }
15 
16     public void destroy() {
17         System.out.println("@Bean-destory-method");
18     }
19 }
使用@Bean形式的Bean
 1 package com.wisely.highlight_spring4.ch2.prepost;
 2 
 3 import javax.annotation.PostConstruct;
 4 import javax.annotation.PreDestroy;
 5 
 6 /**
 7  * 使用JSR250形式的bean
 8  */
 9 public class JSR250WayService {
10     //@PostConstruct:在構造函數執行完以後執行
11     @PostConstruct
12     public void init(){
13         System.out.println("jsr250-init-method");
14     }
15     public JSR250WayService() {
16         super();
17         System.out.println("初始化構造函數-JSR250WayService");
18     }
19     //@PreDestroy:在bean銷燬以前執行
20     @PreDestroy
21     public void destroy(){
22         System.out.println("jsr250-destory-method");
23     }
24 
25 }
使用JSR250形式的bean
 1 package com.wisely.highlight_spring4.ch2.prepost;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.ComponentScan;
 5 import org.springframework.context.annotation.Configuration;
 6 
 7 /**
 8  * 配置類
 9  */
10 @Configuration
11 @ComponentScan("com.wisely.highlight_spring4.ch2.prepost")
12 public class PrePostConfig {
13     //指定BeanWayService的init方法和destroy方法在構造函數以後/bean銷燬以前執行。
14     @Bean(initMethod="init",destroyMethod="destroy")
15     BeanWayService beanWayService(){
16         return new BeanWayService();
17     }
18     
19     @Bean
20     JSR250WayService jsr250WayService(){
21         return new JSR250WayService();
22     }
23 
24 }
配置類
 1 package com.wisely.highlight_spring4.ch2.prepost;
 2 
 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4 
 5 public class Main {
 6     
 7     public static void main(String[] args) {
 8         AnnotationConfigApplicationContext context =
 9                 new AnnotationConfigApplicationContext(PrePostConfig.class);
10         
11         BeanWayService beanWayService = context.getBean(BeanWayService.class);
12         JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);
13         
14         context.close();
15     }
16 
17 }
運行

 

Profile

  Profile爲在不一樣環境下使用不一樣的配置提供了支持(開發環境下的配置和生產環境下的配置確定是不一樣的,例如數據庫的配置)。spring

  有三種方式能夠配置環境數據庫

    1)經過設定Environment的ActiveProfiles來設定當前context須要使用的配置環境。在開發中使用@Profile註解類或方法,達到在不一樣狀況下選擇實例化不一樣的Bean。apache

    2)經過設置jvm的spring.profiles.active參數來設置配置環境。session

    3)Web項目設置在Servlet的context parameter中。app

1 <!--Servlet3.0及以上-->
2 <servlet>
3     <servlet-name>dispatcher</servlet-name>
4     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
5     <init-param>
6         <param-name>spring.profiles.active</param-name>
7         <param-value>production</param-value>
8     </init-param>
9 </servlet>
1 /**
2  * Servlet3.0及以上
3  */
4 public class WebInit implements WebApplicationInitializer {
5     @Override
6     public void onStartup(ServletContext context) throws ServletException {
7         container.setInitParameter("spring.profiles.default", "dev");
8     }
9 }

 

 1 package com.wisely.highlight_spring4.ch2.profile;
 2 
 3 /**
 4  * 示例bean
 5  */
 6 public class DemoBean {
 7 
 8     private String content;
 9 
10     public DemoBean(String content) {
11         super();
12         this.content = content;
13     }
14 
15     public String getContent() {
16         return content;
17     }
18 
19     public void setContent(String content) {
20         this.content = content;
21     }
22     
23 }
示例bean
 1 package com.wisely.highlight_spring4.ch2.profile;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.context.annotation.Profile;
 6 
 7 /**
 8  * Profile配置
 9  */
10 @Configuration
11 public class ProfileConfig {
12     @Bean
13     @Profile("dev")//Profile爲dev時實例化devDemoBean
14     public DemoBean devDemoBean() {
15         return new DemoBean("from development profile");
16     }
17 
18     @Bean
19     @Profile("prod")//Profile爲prod時實例化prodDemoBean
20     public DemoBean prodDemoBean() {
21         return new DemoBean("from production profile");
22     }
23 
24 }
Profile配置
 1 package com.wisely.highlight_spring4.ch2.profile;
 2 
 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4 
 5 public class Main {
 6 
 7     public static void main(String[] args) {
 8           AnnotationConfigApplicationContext context =  
 9                   new AnnotationConfigApplicationContext();
10           
11           context.getEnvironment().setActiveProfiles("dev");//先將活動的profile設置爲dev
12           context.register(ProfileConfig.class);//而後註冊bean配置類,否則會報bean未定義的錯誤
13           context.refresh(); //刷新容器
14           
15           DemoBean demoBean = context.getBean(DemoBean.class);
16           
17           System.out.println(demoBean.getContent());
18           
19           context.close();
20     }
21 }
運行

 

事件(Application Event)

  spring的事件爲bean和bean之間的消息通訊提供了支持。當一個bean處理完一個任務以後,但願另一個bean知道並能作出相應的處理,這時咱們就須要讓另一個bean監聽當前bean所發送的事件。dom

  spring的事件須要遵循以下流程:jvm

    1)自定義事件,繼承ApplicationEvent。ide

    2)定義事件監聽器,實現ApplicationListener。

    3)使用容器發佈事件。

 1 package com.wisely.highlight_spring4.ch2.event;
 2 
 3 import org.springframework.context.ApplicationEvent;
 4 
 5 /**
 6  * 自定義事件
 7  */
 8 public class DemoEvent extends ApplicationEvent{
 9     private static final long serialVersionUID = 1L;
10     private String msg;
11     public DemoEvent(Object source,String msg) {
12         super(source);
13         this.msg = msg;
14     }
15     public String getMsg() {
16         return msg;
17     }
18     public void setMsg(String msg) {
19         this.msg = msg;
20     }
21 }
自定義事件
 1 package com.wisely.highlight_spring4.ch2.event;
 2 
 3 import org.springframework.context.ApplicationListener;
 4 import org.springframework.stereotype.Component;
 5 
 6 /**
 7  * 事件監聽器,實現ApplicationListener接口,並指定監聽的事件類型
 8  */
 9 @Component
10 public class DemoListener implements ApplicationListener<DemoEvent> {
11 
12     /**
13      * 使用onApplicationEvent方法對消息進行接收處理
14      * @param event
15      */
16     public void onApplicationEvent(DemoEvent event) {
17         String msg = event.getMsg();
18         System.out.println("我(bean-demoListener)接受到了bean-demoPublisher發佈的消息:"+ msg);
19     }
20 }
事件監聽器,實現ApplicationListener接口,並指定監聽的事件類型
 1 package com.wisely.highlight_spring4.ch2.event;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.stereotype.Component;
 6 
 7 /**
 8  * 事件發佈類
 9  */
10 @Component
11 public class DemoPublisher {
12     @Autowired
13     ApplicationContext applicationContext;//注入ApplicationContext用來發布事件
14 
15     public void publish(String msg){
16         //使用ApplicationContext的publishEvent方法發佈事件
17         applicationContext.publishEvent(new DemoEvent(this, msg));
18     }
19 }
事件發佈類
 1 package com.wisely.highlight_spring4.ch2.event;
 2 
 3 import org.springframework.context.annotation.ComponentScan;
 4 import org.springframework.context.annotation.Configuration;
 5 
 6 @Configuration
 7 @ComponentScan("com.wisely.highlight_spring4.ch2.event")
 8 public class EventConfig {
 9 
10 }
配置類
 1 package com.wisely.highlight_spring4.ch2.event;
 2 
 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4 public class Main {
 5     public static void main(String[] args) {
 6          AnnotationConfigApplicationContext context =
 7                     new AnnotationConfigApplicationContext(EventConfig.class);
 8          DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
 9          demoPublisher.publish("hello application event");
10          context.close();
11     }
12 }
運行
相關文章
相關標籤/搜索