2023-01-17
一、Spring管理druid步驟
(1)匯入jar包
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency>
(2)撰寫db.properties組態檔
在“模塊名.src.main.resources”下創建“db.properties”
#里面存放的資料格式為key=value db.driverClassName=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/db220106?serverTimezone=UTC
db.username=用戶名
db.password=密碼
(3)撰寫applicationContext.xml相關代碼
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加載外部屬性檔案db.properties--> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <!-- 裝配資料源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${db.driverClassName}"></property> <property name="url" value="${db.url}"></property> <property name="username" value="${db.username}"></property> <property name="password" value="${db.password}"></property> </bean> </beans>
二、Bean的作用域
1、語法:
在bean標簽中加一個“scope”屬性即可,
2、四個作用域
(1)singleton(默認值)
單例(在容器中只有一個物件)
創建容器物件時,spring創建物件
(2)prototype
多例(在容器中有多個物件)
(3)request:請求域
當前請求有效,離開請求域失效
當前請求:URL不變即為當前請求
(4)session:會話域
當前會話,當前瀏覽器不關閉不更換即為當前會話,
三、Spring中Bean的生命周期
1、生命周期的程序:
①通過構造器或工廠方法創建bean實體
②為bean的屬性設定值和對其他bean的參考
③呼叫bean的初始化方法
④bean可以使用了
⑤當容器關閉時,呼叫bean的銷毀方法
四、bean的后置處理器
1、作用:在呼叫初始化方法前后對bean進行額外的處理,
2、實作:
(1)實作BeanPostProcessor介面
(2)重寫方法
①postProcessBeforeInitialization(Object,String):在bean的初始化之前執行
②postProcessAfterInitialization(Object,String):在bean的初始化之后執行
(3)注意
裝配后置處理器會為每個bean均裝配,不能為區域bean裝配后置處理器
五、Spring中自動裝配
1、Spring中提供兩種裝配方式
(1)自動裝配
(2)手動裝配
2、Spring自動裝配語法及規則
在bean標簽中添加屬性:Autowire即可
(1)byName
物件中屬性與容器中的beanId進行匹配,如果屬性名與beanId數值一致,則自動裝配成功
(2)byType
物件中屬性型別與容器中class進行匹配,如果唯一匹配則自動裝配成功
①匹配0個:未裝配
②匹配多個:會報錯
(3)基于XML方式的自動裝配,只能裝配“非字面量”數值
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/542130.html
標籤:其他
上一篇:Python實作抽獎程式
