1. 程式人生 > >JAVAEE顛覆者,SpringBoot實戰一書學習小記(Bean的Scope,Bean的動態注入,Bean初始化和銷燬)

JAVAEE顛覆者,SpringBoot實戰一書學習小記(Bean的Scope,Bean的動態注入,Bean初始化和銷燬)

Bean的Scope

每一個bean可以新增Scope標籤來設定

個人理解從此看出Spring的控制反轉預設一直都在用一個例項注入

1.Singleton 一個Spring容器中只有一個Bean的例項,此為Spring的預設配置,全容器共享一個例項。

2.Prototype 每次呼叫一個新建一個Bean的例項

3.Request Web專案中,給每一個http request 新建一個Bean例項。

4.Session Web專案中,給每一個http session新建一個Bean例項。

5.GlobalSession 這個只在portal應用中有用,給每一個global http session 新建一個例項。

可以拿小例子是演示一下預設的singleton 和 Prototype的結果

建立一個空的service,一個標註上@Scope("prototye") ,一個預設

@Service
@Scope("prototype")
public class DemoPrototypeService {

}
@Service
public class DemoSingletonService {

}

在config類加入掃描包註解

@Configuration
@ComponentScan("com.cn.sola.service")
public class SpringConfig {

}

然後用反射在測試類測試看結果

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootShiZhanApplicationTests {

	@Test
	public void contextLoads() {
		
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
	
	DemoSingletonService d1 = context.getBean(DemoSingletonService.class);
	DemoSingletonService d2 = context.getBean(DemoSingletonService.class);
	
	System.out.println(d1.equals(d2));
	
	DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
	DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);
	
	System.out.println(p1.equals(p2));
	}

}

結果就是DemoSingletonService結果為True,DemoPrototypeService為False。

由此看出Spring加Bean註解的都是一個例項。

Spring EL和資源的呼叫

未來的大牛

簡單來說就是例如註解直接注入變數的值

首先為了方便先加入一個io工具依賴

		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.6</version>
		</dependency>

然後可以在com.cn.sola包下建立一個test.properties,一個test.txt

比如test.properties裡可以寫

book.author=solatest
book.name=spring boot

txt可以寫

未來的大牛

需要注入的bean(其中一個service)

package com.cn.sola.service;

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

@Service
public class DemoService {
	@Value("其他類的屬性")
	private String another;

	public String getAnother() {
		return another;
	}

	public void setAnother(String another) {
		this.another = another;
	}

}

另一個service

package com.cn.sola.service;

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;
import org.springframework.stereotype.Service;

@Service
public class SpringService {
	//直接注入字串
	@Value("I Love You!")
	private String normal;
	
	//注入當前系統的操作環境(當前結果window10)
	@Value("#{systemProperties['os.name']}")
	private String osName;
	
	//注入一個隨機數
	@Value("#{T(java.lang.Math).random()*100.0}")
	private double randomNumber;
    
	//注入demoService下String型別another引數的值
	@Value("#{demoService.another}")
	private String fromAnother;
	
	//注入了一個檔案型別
	@Value("classpath:com/cn/sola/bean/test.txt")
	private Resource testFile;
	
	//暫時不明
	@Value("http://www.baidu.com")
	private Resource testUrl;
	
	//注入了test.properties下book.name的值
	@Value("${book.name}")
	private String bookName;
	
	//這類應該是可以直接獲取properties的鍵值對
	@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);
			
			//commons-io依賴的方法
			System.out.println(IOUtils.toString(testFile.getInputStream()));
			System.out.println(IOUtils.toString(testUrl.getInputStream()));
			System.out.println(bookName);
			//用這個方法可以用key值獲取到value,但是也要宣告properties的位置@PropertySource("classpath:com/cn/sola/bean/test.properties")
			System.out.println(environment.getProperty("book.author"));
		}catch(Exception e){
			
			e.printStackTrace();
		}
	}
	
	
}

配置類

package com.cn.sola.config;

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

@Configuration
@ComponentScan("com.cn.sola.service")
@PropertySource("classpath:com/cn/sola/bean/test.properties")
public class ResourceConfig {

}

測試類

package com.cn.sola;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

import com.cn.sola.config.ResourceConfig;
import com.cn.sola.service.SpringService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootShiZhanApplicationTests {

	@Test
	public void contextLoads() {
		
	   AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ResourceConfig.class);
	
	   SpringService service = context.getBean(SpringService.class);
	   
	   service.outputResource();
	   
	   context.close();
	}

}

輸出結果就和想象的一樣啦------------

Bean的初始化和銷燬

首先新增一個依賴,原文中用的JSR-250,現在只用這個就可以

		<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>javax.annotation-api</artifactId>
			<version>1.3.2</version>
		</dependency>

我們實際開發的時候,經常會遇到在Bean在使用之前或者之後做些必要的操作,Spring對Bean的生命週期的操作提供了支援

有兩種方式

(1)Java配置方式:使用@Bean的initMethod 和 destroyMethod例子 //這個在配置類裡寫

  (2)  註解方式:需要新增依賴利用JSR-250的@PostConstruct和@PreDestroy    //JSR-250現在已經包含在

使用@Bean形式的Bean   得在配置類裡宣告

package com.cn.sola.service;

public class BeanWayService {

	public void init(){
		
		System.out.println("@Bean-init-method");
	}
	public BeanWayService(){
		super();
		System.out.println("初始化建構函式-BeanWayService");
	}
	public void destroy(){
		
		System.out.println("@Bean-destroy-method");
	}
}

使用JSR250形式的Bean  在類裡就可宣告

package com.cn.sola.service;

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

public class JSR250WayService {
	
	@PostConstruct
	public void init(){
		System.out.println("jsr250-init-method");
	}
	public JSR250WayService(){
		super();
		System.out.println("初始化構造引數-JSR250WayService");
	}
	@PreDestroy
	public void destroy(){
		System.out.println("jsr250-destory-method");
	}

}

配置類     @Bean配置在此配置初始和銷燬方法

package com.cn.sola.config;

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 com.cn.sola.service.BeanWayService;
import com.cn.sola.service.JSR250WayService;

@Configuration
@ComponentScan("com.cn.sola.service")
public class ResourceConfig {

	@Bean(initMethod="init",destroyMethod="destroy")//這裡可以設定初始的呼叫方法
	BeanWayService beanWayService(){
		return new BeanWayService();
	}
	@Bean
	JSR250WayService jsr250WayService(){
		return new JSR250WayService();
	}
	
}

下面是小測試類

package com.cn.sola;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

import com.cn.sola.config.ResourceConfig;
import com.cn.sola.service.BeanWayService;
import com.cn.sola.service.JSR250WayService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootShiZhanApplicationTests {

	@Test
	public void contextLoads() {
		
	   AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ResourceConfig.class);
	
	   context.getBean(BeanWayService.class);
	   
	   context.getBean(JSR250WayService.class);
	   
	   context.close();
	}

}
下面是結果
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.3.RELEASE)

2018-07-05 19:41:12.182  INFO 9204 --- [           main] c.c.s.SpringBootShiZhanApplicationTests  : Starting SpringBootShiZhanApplicationTests on DESKTOP-LN7MO04 with PID 9204 (started by JAVA in D:\SpringBootWorkSpace\SpringBootShiZhan)
2018-07-05 19:41:12.184  INFO 9204 --- [           main] c.c.s.SpringBootShiZhanApplicationTests  : No active profile set, falling back to default profiles: default
初始化建構函式-BeanWayService
@Bean-init-method
初始化構造引數-JSR250WayService
jsr250-init-method
2018-07-05 19:41:14.125  INFO 9204 --- [           main] c.c.s.SpringBootShiZhanApplicationTests  : Started SpringBootShiZhanApplicationTests in 2.285 seconds (JVM running for 3.023)
2018-07-05 19:41:14.240  INFO 9204 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]5c20ffa8: startup date [Thu Jul 05 19:41:14 CST 2018]; root of context hierarchy
初始化建構函式-BeanWayService
@Bean-init-method
初始化構造引數-JSR250WayService
jsr250-init-method
2018-07-05 19:41:14.278  INFO 9204 --- [           main] s.c.a.AnnotationConfigApplicationContext : Closing org.spring[email protected]5c20ffa8: startup date [Thu Jul 05 19:41:14 CST 2018]; root of context hierarchy
jsr250-destory-method
@Bean-destroy-method
jsr250-destory-method
@Bean-destroy-method



相關推薦

JAVAEE顛覆SpringBoot實戰學習小記Bean的ScopeBean動態注入Bean初始銷燬

Bean的Scope每一個bean可以新增Scope標籤來設定個人理解從此看出Spring的控制反轉預設一直都在用一個例項注入1.Singleton 一個Spring容器中只有一個Bean的例項,此為Spring的預設配置,全容器共享一個例項。2.Prototype 每次呼叫

JAVAEE顛覆SpringBoot實戰學習小記ProfileapplicationEvent

Profile概念profile為在不同環境下使用不通的配置提供了支援(開發環境下的配置和生產環境下的配置肯定不同的,例如資料庫的配置)。首先建立一個beanpackage com.cn.sola.bean; public class DemoBean { privat

JavaEE顛覆:spring-boot實戰原始碼

在當今Java EE 開發中,Spring 框架是當之無愧的王者。而Spring Boot 是Spring 主推的基於“習慣優於配置”的原則,讓你能夠快速搭建應用的框架,從而使得Java EE 開發變得異常簡單。 《JavaEE開發的顛覆者: Spring B

FFmpeg:常見結構體的初始銷燬AVFormatContextAVFrame等——雷神神文

===================================================== FFmpeg的庫函式原始碼分析文章列表: 【架構圖】 【通用】 【解碼】 【編碼】

FFmpeg原始碼簡單分析:常見結構體的初始銷燬AVFormatContextAVFrame等

=====================================================FFmpeg的庫函式原始碼分析文章列表:【架構圖】【通用】【解碼】【編碼】【其它】【指令碼】【H.264】================================

【Spring註解驅動開發】如何使用@Bean註解指定初始銷燬的方法?看這篇就夠了!!

## 寫在前面 > 在【[String註解驅動開發專題](https://www.cnblogs.com/binghe001/category/1780611.html)】中,前面的文章我們主要講了有關於如何向Spring容器中註冊bean的知識,大家可以到【[String註解驅動開發專題](http

JavaEE開發的顛覆 Spring Boot實戰--筆記

發的 技術 .com bubuko com font PE span 學習 Spring 的問題 Spring boot的特點,沒有特別的地方 1.Spring 基礎 PS:關於spring配置 PS:Spring 生態 2.Spring 常用配置 PS: spr

javaEE顛覆程式碼

ps : 只是單純的打了一遍 / javaEE顛覆者第一章 1.3.1 依賴注入 我是直接用maven來建立專案的 關於maven的安裝 這裡就不在多加描述了 直接開始吧 這是po

JavaEE開發的顛覆 Spring Boot實戰 完整版》電子書+專案例子 百度網盤連結

《JavaEE開發的顛覆者 Spring Boot實戰  完整版》電子書+專案例子 百度網盤連結: 連結:https://pan.baidu.com/s/1uuHKMWUNs1O9aUtJycpVaA 密碼:zf3f

solr分布式索引【實戰、分片配置讀取:工具類configUtil.java讀取配置代碼片段配置實例】

hset fileinput string lose eas hash hashset mod bject 1 private static Properties prop = new Properties(); 2 3 private stati

SpringBoot實戰()之構建RestFul風格

周期 enable alias gree 控制 我的博客 import 啟動 def RestFul風格是一種非常流行的架構風格,相關實戰可以參考我的這篇博客:SSM框架之RestFul示例 論文可參考:https://www.ics.uci.edu/~fielding/p

【Java爬蟲學習】WebMagic框架爬蟲學習實戰:爬取網易雲歌單資訊並存入mysql中

最近,需要使用Java進行爬蟲編寫,就去學了Java的爬蟲。因為之前學習了Scrapy框架,所以學Java的爬蟲使用了WebMagic框架,這個框架是基於Scrapy框架開發的。大家有興趣可以去看看操作文件:  這個框架是國人開發的,所以說明文件都是中文,簡單易懂。

Python爬蟲學習實戰糗事百科2017/7/21更新

前言 這幾天學習爬蟲,網上看了一些教程,發現這個 http://cuiqingcai.com/990.html 是相當不錯的。 但可惜的是,整個教程是兩年前的,但是Python是2.x版本的,跟現在的3.x有一些基本的語法不同;還有糗事百科也經過了改版。 總

zookeeper實現分散式鎖總結看這篇足矣設計模式應用實戰

zk實現分散式鎖縱觀網路各種各樣的帖子層出不窮,筆者查閱很多資料發現一個問題,有些文章只寫原理並沒有具體實現,有些文章雖然寫了實現但是並不全面 借這個週末給大家做一個總結,程式碼拿來就可以用並且每一種實現都經過了測試沒有bug。下面我們先從最簡單的實現開始介紹: 簡單的實現 package com.sr

HTTP的請求方法共有9種有OPTIONS, HEAD, GET, POST等等消息頭有圖十分清楚

ram () 哪些 ive 十分 enc set utf-8 cat 請求方法:指定了客戶端想對指定的資源/服務器作何種操作 下面我們介紹HTTP/1.1中可用的請求方法: 【GET:獲取資源】 GET方法用來請求已被URI識別的資源。指定的資源經服務器端解析後返

JS中如何判斷個數是不是小數?如果是小數如何判斷它是幾位小數??

nts text else lin var length code 判斷 alt <script type="text/javascript"> var x = 4.23323;//測試的數字 var y = String(x).indexOf(

*要快速學習SSM框架你需要學習曲線平滑的教程

lan 都是 spring 學習方式 能夠 分享圖片 個人能力 很多 data 作者:meepo鏈接:https://www.zhihu.com/question/57719761/answer/156952139來源:知乎著作權歸作者所有。商業轉載請聯系作者獲得授權,非商

egret 簡單的筆畫算法在wing中可以直接跑以後玩這類遊戲就有個作弊器了

com ast font 必須 ech upd length reat ini /** * 在Main中創建遊戲場景 * Create a game scene */ private createGameScene() { Mt

前端 高階 二十五vue2.0專案實戰 配置簡要說明、程式碼簡要說明、Import/Export、輪播列表例子

一、啟動服務自動開啟瀏覽器執行 二、配置簡要說明 1、node_modules   安裝好的依賴檔案,中介軟體等,所在位置   2、package.jason    配置當前專案要安裝的中介軟體和依賴檔案 { "name": "my-app", "ver

劍指offer_1:給你根長度為n的繩子把繩子剪成m段m、n都是整數且m > 1, n > 1,m段繩子的長度依然是整數求m段繩子的長度乘積最大為多少?  * 比如繩子長度為8我們可以分成

<code> package Chap2; /**問題描述  * 給你一根長度為n的繩子,把繩子剪成m段(m、n都是整數且m > 1, n > 1),m段繩子的長度依然是整數,求m段繩子的長度乘積最大為多少?  * 比如繩子長度為8,我們可以分成2