zoukankan      html  css  js  c++  java
  • Spring常用配置

    概述

      本文主要讲解Spring的一些常用配置,使用Java Bean来配置。

      需要注意的均写在注释里面了。


    配置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为在不同环境下使用不同的配置提供了支持(开发环境下的配置和生产环境下的配置肯定是不同的,例如数据库的配置)。

      有三种方式可以配置环境

        1)通过设定Environment的ActiveProfiles来设定当前context需要使用的配置环境。在开发中使用@Profile注解类或方法,达到在不同情况下选择实例化不同的Bean。

        2)通过设置jvm的spring.profiles.active参数来设置配置环境。

        3)Web项目设置在Servlet的context parameter中。

    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所发送的事件。

      spring的事件需要遵循如下流程:

        1)自定义事件,继承ApplicationEvent。

        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 }
    运行
  • 相关阅读:
    [APM] OneAPM 云监控部署与试用体验
    Elastic Stack 安装
    xBIM 综合使用案例与 ASP.NET MVC 集成(一)
    JQuery DataTables Selected Row
    力导向图Demo
    WPF ViewModelLocator
    Syncfusion SfDataGrid 导出Excel
    HTML Table to Json
    .net core 2.0 虚拟目录下载 Android Apk 等文件
    在BootStrap的modal中使用Select2
  • 原文地址:https://www.cnblogs.com/gaofei-1/p/8698101.html
Copyright © 2011-2022 走看看