1. 程式人生 > >SpringBoot實戰筆記:03_Spring常用配置

SpringBoot實戰筆記:03_Spring常用配置

Spring常用配置

1,Bean的Scope

//預設是Singleton,相當於@Scope("singleton"),單例
@Service
public class DefaultScopeService{
}

@Service
@Scope("prototype")//宣告為prototype,每次獲得都會建立一個新的
public class DefaultScopeService{
}

2,Spring EL-Spring及資源呼叫

01,建立show.properties檔案

    author=zyf
    name=BaseSpringConfig
02,建立show.txt檔案

    此去經年,應是良辰好景虛設。
03,增添pom.xml中的依賴於配置
<!--03_新的依賴:簡化檔案相關操作-->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.2</version>
</dependency>
<!--在build標籤中增添如下標籤,將對應檔案字尾名的檔案,加入到編譯後的類(Class位元組碼檔案)路徑中-->
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.txt</include> </includes> <!--不過濾上述字尾名的檔案--> <filtering>false</filtering
>
</resource> </resources>
1,建立ELConfig配置類檔案
package com.zyf;

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.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;

import java.io.IOException;

/**
 * Created by zyf on 2018/3/2.
 */
@Configuration
@ComponentScan("com.zyf")
@PropertySource("classpath:com/zyf/show.properties")//指定資原始檔的路徑
public class ELConfig {

    //1,注入普通字串
    @Value("便縱用萬種風情,更與何人說")
    private String normal;

    //2,注入作業系統屬性
    @Value("#{systemProperties['os.name']}")
    private String osName;

    //3,注入表示式的結果,呼叫Math類靜態方法 * 100.0得到的結果
    @Value("#{T(java.lang.Math).random() * 100.0}")
    private double randomNumber;

    //4,注入其它bean的屬性
    @Value("#{demoService.another}")
    private String fromAnother;

    //5,注入檔案資源
    @Value("classpath:com/zyf/show.txt")
    private Resource showFile;

    //6,注入網址資源
    @Value("http://www.baidu.com")
    private Resource baiduUrl;

    //7,注入資原始檔(.properties)中的內容
    //已經通過PropertySource指定了資原始檔的路徑
    @Value("${name}")
    private String name;

    //7,若要使用value注入,則需要搭配如下靜態方法
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }

    //7,注入資原始檔後,也可以在environment物件中獲得資原始檔中的內容
    @Autowired
    private Environment environment;

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

            System.out.println(IOUtils.toString(showFile.getInputStream()));
            System.out.println(IOUtils.toString(baiduUrl.getInputStream()));
            System.out.println("name:---"+name);
            System.out.println("environment.getProperty('author'):---"+environment.getProperty("author"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
2,測試
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(ELConfig.class);
        ELConfig bean = context.getBean(ELConfig.class);
        bean.outputResource();

        context.close();
    }
}
3,測試結果

3,Bean的初始化和銷燬

有時需要在Bean使用之前或之後做些必要的操作,Spring對Bean的生命週期的操作提供了支援。

  • Java配置方式:使用 @BeaninitMethoddestroyMethod
  • 註解方式:利用JSR250的 @PostConstruct@PreDestroy
0,在pom.xml中增加JSR250的依賴庫
<!--03_新的依賴:提供bean初始化與銷燬註解的支援-->
<dependency>
  <groupId>javax.annotation</groupId>
  <artifactId>jsr250-api</artifactId>
  <version>1.0</version>
</dependency>
1,建立BeanService類
package com.zyf;

/**
 * Created by zyf on 2018/3/2.
 * 使用@Bean形式的Bean
 */
public class BeanService {

    public void init(){
        System.out.println("@Bean-init-method");
    }

    public BeanService() {
        System.out.println("初始化構造方法-BeanService");
    }

    public void destroy(){
        System.out.println("@Bean-destroy-method");
    }

}
2,建立JSR250Service類
package com.zyf;

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

/**
 * Created by zyf on 2018/3/2.
 */
public class JSR250Service {

    @PostConstruct
    public void init(){
        System.out.println("jsr250-init-method");

    }

    public JSR250Service() {
        System.out.println("構造方法:JSR250Service");

    }

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

}
3,建立InitDesConfig配置類
package com.zyf;

import org.springframework.context.annotation.Bean;

/**
 * Created by zyf on 2018/3/2.
 */
public class InitDesConfig {

    //需要手動指定哪個方法是init
    @Bean(initMethod = "init",destroyMethod = "destroy")
    public BeanService beanService(){
        return new BeanService();
    }


    //已經在JSR250類內部通過註解指定了
    @Bean
    public JSR250Service jsr250Service(){
        return new JSR250Service();
    }

}
4,測試
package com.zyf;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by zyf on 2018/3/2.
 */
public class InitDesMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(InitDesConfig.class);

        JSR250Service jsr250Service = context.getBean(JSR250Service.class);
        BeanService beanService = context.getBean(BeanService.class);
    }
}
5,測試結果