springboot学习章节-spring常用配置

1、Scope

package com.zhen.highlights_spring4.ch2.scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * @author zhen
 * @Date 2018/6/12 11:38
 */
@Service
@Scope("prototype")
public class DemoPrototypeService {
}
package com.zhen.highlights_spring4.ch2.scope;

import org.springframework.stereotype.Service;

/**
 * @author zhen
 * @Date 2018/6/12 11:37
 */
@Service
public class DemoSingletonService {
}
package com.zhen.highlights_spring4.ch2.scope;

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

/**
 * @author zhen
 * @Date 2018/6/12 11:38
 */
@Configuration
@ComponentScan("com.zhen.highlights_spring4.ch2.scope")
public class ScopeConfig {
}
package com.zhen.highlights_spring4.ch2.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author zhen
 * @Date 2018/6/12 11:39
 */
public class Main {
    public static void main(String[] args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
        DemoPrototypeService demoPrototypeService = context.getBean(DemoPrototypeService.class);
        DemoPrototypeService demoPrototypeService1 = context.getBean(DemoPrototypeService.class);
        System.out.println("demoPrototypeService1 == demoPrototypeService 结果是:" + (demoPrototypeService == demoPrototypeService1));

        DemoSingletonService demoSingletonService = context.getBean(DemoSingletonService.class);
        DemoSingletonService demoSingletonService1 = context.getBean(DemoSingletonService.class);
        System.out.println("demoSingletonService1 == demoSingletonService 结果是:" + (demoSingletonService == demoSingletonService1));

        context.close();
    }
}

2、Spring EL

book.author=wangyunfei
book.name=spring boot

test.properties

你好

test.txt

package com.zhen.highlights_spring4.ch2.el;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author zhen
 * @Date 2018/6/12 11:57
 */
@Service
public class DemoService {

    @Value("其他类的属性")
    private String another;

    public String getAnother() {
        return another;
    }

    public void setAnother(String another) {
        this.another = another;
    }
}
package com.zhen.highlights_spring4.ch2.el;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

/**
 * @author zhen
 * @Date 2018/6/12 11:58
 */
@Configuration
@ComponentScan("com.zhen.highlights_spring4.ch2.el")
@PropertySource("classpath:com/zhen/highlights_spring4/ch2/el/test.properties")
public class ElConfig {

    @Value("I Love You")
    private String normal;

    @Value("#{systemProperties[‘os.name‘]}")
    private String osName;

    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber;

    @Value("#{demoService.another}")
    private String fromAnother;

    @Value("classpath:com/zhen/highlights_spring4/ch2/el/test.txt")
    private Resource testFile;

    @Value("http://www.baidu.com")
    private Resource testUrl;

    @Value("${book.name}")
    private String bookName;

    @Autowired
    private Environment environment;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigure(){
        return new PropertySourcesPlaceholderConfigurer();
    }

    public void outputResource(){
        try{
            System.out.println(normal);
            System.out.println(osName);
            System.out.println(randomNumber);
            System.out.println(fromAnother);

            System.out.println(IOUtils.toString(testFile.getInputStream()));
            System.out.println(IOUtils.toString(testUrl.getInputStream()));
            System.out.println(bookName);
            System.out.println(environment.getProperty("book.author"));
        }catch (Exception e){

        }
    }

}
package com.zhen.highlights_spring4.ch2.el;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author zhen
 * @Date 2018/6/12 12:15
 */
public class Main {
    public static void main(String[] args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ElConfig.class);
        ElConfig reourceService = context.getBean(ElConfig.class);

        reourceService.outputResource();

        context.close();
    }
}

3、初始化和销毁

package com.zhen.highlights_spring4.ch2.prepost;

/**
 * @author zhen
 * @Date 2018/6/12 13:13
 */
public class BeanWayService {
    public void init(){
        System.out.println("@Bean-init-method");
    }

    public BeanWayService(){
        super();
        System.out.println("初始化构造函数-BeanWayService");
    }
    public void destory(){
        System.out.println("@Bean-destory-method");
    }
}
package com.zhen.highlights_spring4.ch2.prepost;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author zhen
 * @Date 2018/6/12 13:17
 */
public class JSR250WayService {
    @PostConstruct
    public void init(){
        System.out.println("jsr250-init-method");
    }

    public JSR250WayService(){
        super();
        System.out.println("初始化构造函数-JSR250WayService");
    }

    @PreDestroy
    public void destory(){
        System.out.println("jsr250-destory-method");
    }

}
package com.zhen.highlights_spring4.ch2.prepost;

import org.springframework.context.annotation.Bean;

/**
 * @author zhen
 * @Date 2018/6/12 13:19
 */
public class PrePostConfig {

    @Bean(initMethod = "init", destroyMethod = "destory")
    BeanWayService beanWayService(){
        return new BeanWayService();
    }

    @Bean
    JSR250WayService jsr250WayService(){
        return new JSR250WayService();
    }
}
package com.zhen.highlights_spring4.ch2.prepost;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author zhen
 * @Date 2018/6/12 13:20
 */
public class Main {

    public static void main(String[] args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrePostConfig.class);

        BeanWayService beanWayService = context.getBean(BeanWayService.class);
        JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);

        context.close();
    }

}

4、profile(为不同环境下使用不同配置提供支持)

package com.zhen.highlights_spring4.ch2.profile;

/**
 * @author zhen
 * @Date 2018/6/12 13:24
 */
public class DemoBean {

    private String content;

    public DemoBean(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
package com.zhen.highlights_spring4.ch2.profile;

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

/**
 * @author zhen
 * @Date 2018/6/12 13:24
 */
@Configuration
public class ProfileConfig {

    @Bean
    @Profile("dev")
    public DemoBean devDemoBean(){
        return new DemoBean("from development profile");
    }

    @Bean
    @Profile("prod")
    public DemoBean prodDemoBean(){
        return new DemoBean("from production profile");
    }
}
package com.zhen.highlights_spring4.ch2.profile;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author zhen
 * @Date 2018/6/12 13:28
 */
public class Main {

    public static void main(String[] args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        context.getEnvironment().setActiveProfiles("dev");
        context.register(ProfileConfig.class);
        context.refresh();

        DemoBean demoBean = context.getBean(DemoBean.class);
        System.out.println(demoBean.getContent());

        context.close();
    }

}

5、事件(为bean与bean消息通信提供支持)

package com.zhen.highlights_spring4.ch2.event;

import org.springframework.context.ApplicationEvent;

/**
 * @author zhen
 * @Date 2018/6/12 13:31
 */
public class DemoEvent extends ApplicationEvent {

    private static final long serialVersionUID = 6639236243302861037L;

    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public DemoEvent(Object source, String msg) {
        super(source);
        this.msg = msg;
    }
}
package com.zhen.highlights_spring4.ch2.event;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @author zhen
 * @Date 2018/6/12 13:34
 */
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
    @Override
    public void onApplicationEvent(DemoEvent demoEvent) {
        String msg = demoEvent.getMsg();
        System.out.println("我(bean-demoListener)接收到了bean-demoPublisher发布的信息:" + msg);
    }
}
package com.zhen.highlights_spring4.ch2.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author zhen
 * @Date 2018/6/12 13:36
 */
@Component
public class DemoPublisher {
    @Autowired
    ApplicationContext applicationContext;

    public void publish(String msg){
        applicationContext.publishEvent(new DemoEvent(this, msg));
    }
}
package com.zhen.highlights_spring4.ch2.event;

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

/**
 * @author zhen
 * @Date 2018/6/12 13:37
 */
@Configuration
@ComponentScan("com.zhen.highlights_spring4.ch2.event")
public class EventConfig {
}
package com.zhen.highlights_spring4.ch2.event;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author zhen
 * @Date 2018/6/12 13:37
 */
public class Main {
    public static void main(String[] args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
        DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
        demoPublisher.publish("hello application event");
        context.close();
    }
}

原文地址:https://www.cnblogs.com/aigeileshei/p/9254823.html

时间: 2024-10-09 06:45:37

springboot学习章节-spring常用配置的相关文章

SpringBoot学习(二)--&gt;Spring的Java配置方式

二.Spring的Java配置方式 Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置. 1.@Configuration 和 @Bean Spring的Java配置方式是通过 @Configuration 和 @Bean 这两个注解实现的: 1.@Configuration 作用于类上,相当于一个xml配置文件: 2.@Bean 作用于方法上,相当于xml配置中的<bean>: 2.示例 该示例演示了通过Java配置的方式进行配置Spring,并且实现了Spring IO

Spring常用配置示例

Spring 是一款Java平台的开源框架,是为解决企业级应用程序开发的复杂性而创建的,通过良好的分层架构让开发人员能够专注于业务逻辑的开发. Spring框架是一个分层架构,由不同的模块组成,构成spring的每个组件或模块都可以单独使用或者多个模块配合使用,以实现不同的功能需求.Spring框架的模块结构如下图所示: SpringCore是Spring框架的核心模块,提供spring框架的基本功能,使用工厂模式BeanFactory通过控制反转(IoC).依赖注入(DI)等实现对beans的

Spring常用配置 Scope

Bean的Scope Scope描述的是Spring容器如何新建Bean的实例的.Spring的Scope有以下几种,通过@Scope注解来实现.    1.Singleton:一个Spring容器中有一个Bean的实例,此为Spring的默认配置,全容器共享一个实例.    2.Prototype: 每次调用新建一个Bean的实例. 实例 编写Singleton的Bean package com.wisely.highlight_spring4.ch2.scope; import org.sp

Spring Boot实战笔记(四)-- Spring常用配置(事件Application Event)

一.事件(Application Event) Spring的事件为Bean和Bean之间的消息通信提供了支持.当一个Bean处理完一个任务之后,希望另一个Bean知道并能做相应的处理,这时我们就需要让另一个Bean监听当前Bean所发送的事情. Spring的事件需要遵循如下流程: (1)自定义事件,集成ApplicationEvent. (2)定义事件监听器,实现ApplicationListener. (3)使用容器发布事件. 示例: 1.自定义事件. package com.ecwork

Spring Boot实战笔记(三)-- Spring常用配置(Bean的初始化和销毁、Profile)

一.Bean的初始化和销毁 在我们的实际开发的时候,经常会遇到Bean在使用之前或之后做些必要的操作,Spring对Bean的生命周期操作提供了支持.在使用Java配置和注解配置下提供如下两种方式: (1)Java配置的方式:使用 @Bean 的 initMethod 和 destroyMethod(相当于xml配置中的 init-method 和 destroy-method). (2)注解方式:利用JSR-250的 @PostContruct 和 @PreDestroy. 演示: 1.增加

Springboot学习七 spring的一些注解

一 事务控制 @Service public class CityServiceImpl implements CityService { @Autowired private CityMapper cityMapper; @Override @Transactional(value = "primaryTxMan", readOnly = true) public List<City> findByState(String state) { return this.cit

Spring Boot实战(2) Spring常用配置

1. Bean的Scope scope描述Spring容器如何新建Bean的实例.通过注解@Scope实现,取值有: a. Singleton:一个Spring容器中只有一个Bean的实例.此为Spring的默认配置,全容器共享一个实例. b. Prototype:每次调用新建一个Bean的实例 c. Request:Web项目中,给每一个Http Request新建一个Bean实例 d. Session:Web项目中,给每一个Http Session新建一个Bean实例 e. GlobalSe

SpringBoot学习(一)-Spring的发展

一.Spring的发展 1.Spring1.x 时代 在Spring1.x时代,都是通过xml文件配置bean,随着项目的不断扩大,需要将xml配置分放到不同的配置文件中,需要频繁的在java类和xml配置文件中切换. 2.Spring2.x时代 随着JDK 1.5带来的注解支持,Spring2.x可以使用注解对Bean进行申明和注入,大大的减少了xml配置文件,同时也大大简化了项目的开发. 那么,问题来了,究竟是应该使用xml还是注解呢? 最佳实践:(IoC推荐注解:AOP推荐配置) 1. 

Spring常用配置(1) --- Bean的Scope

1.Bean的Scope 1.1.理论 Scope描述的是Spring容器如何新建Bean的实例,可以通过@Scope注解实现 Singleton:默认配置,一个Spring容器中只有一个Bean的实例,全容器共享一个实例. Prototype:每次调用新建一个Bean实例. Request:Web项目中,给每一个http request 新建一个Bean实例. Session:Web项目中,给每一个http request 新建一个Bean实例. GlobalSession:这个旨在prota