「2020最新」Spring最易學習教程—IOC 以及 整合Struts2

0 複習

  1. 工廠設計模式mysql

    使用工廠代替new模式建立對象,目的:解耦合web

  2. Spring工廠的使用spring

    applicationContext.xml中配置 bean標籤sql

    編碼:建立工廠,從工廠中獲取對象數據庫

  3. Spring中屬性注入apache

    1. 簡單類型(基本類型+包裝類+String)編程

      <bean id="標識名" class="全類名">
       <property name="屬性">
           <value></value>
          </property>
          <property name="屬性" value="值"/>
      </bean>
    2. 對象類型設計模式

      <bean id="a" class="Address的全類名">
       <property name="屬性1" value="值1"/>
          <property name="屬性2" value="值2"/>
      </bean>

      <bean id="p" class="Person全類名">
       <property name="addr">
           <ref bean="a"/>
          </property>
      </bean>
      <bean id="p2" class="Person全類名">
       <property name="addr" ref="a"/>
      </bean>
    3. 數組+List+Set數組

    4. Map+Propertiestomcat

1 注入補充

1.1 null值

當須要顯式的爲屬性賦值爲 null 時,經過 null標籤完成。

<bean id="u" class="com.bcl.entity.User">
    <constructor-arg value="1" index="0"/>
    <constructor-arg value="xiaohei" index="1"/>
    <constructor-arg index="2"><null/></constructor-arg>
</bean>

1.2 內部bean

<bean id="a" class="com.bcl.entity.Address">
    <property name="street" value="文化路"/>
    <property name="city" value="硅谷"/>
</bean>

<bean id="p" class="com.bcl.entity.Person">
    <property name="personId" value="1"/>
    <property name="personName" value="xiaohei"/>
    <property name="addr" ref="a"/>
</bean>

可使用內部bean替換的寫法
<bean id="p" class="com.bcl.entity.Person">
    <property name="personId" value="1"/>
    <property name="personName" value="xiaohei"/>
    <property name="addr" >
        <bean class="com.bcl.entity.Address">
            <property name="city" value="鄭州"/>
            <property name="street" value="文化路"/>
        </bean>
    </property>
</bean>

2 FactoryBean技術(建立複雜對象)

2.1 FactoryBean引言

Spring工廠要管理程序中各類種類的對象。

image-20200601102514322

2.2 FactoryBean的開發步驟

  1. 編碼  實現FactoryBean接口

    public class ConnectionFactoryBean implements FactoryBean<Connection{
        @Override
        //返回複雜對象
        public Connection getObject() throws Exception {
            //1 加載驅動
            Class.forName("com.mysql.jdbc.Driver");
            //2 創建鏈接
            String url="jdbc:mysql://localhost:3306/bcl2002?useUnicode=true&characterEncoding=utf8";
            String username="root";
            String password="root";
            Connection conn = DriverManager.getConnection(url, username, password);
            return conn;
        }

        @Override
        //返回複雜對象的類型
        public Class<?> getObjectType() {
            return Connection.class;
        }

        @Override
        //複雜對象是否單例  true:單例  false:多例
        public boolean isSingleton() {
            return true;
        }
    }
  2. 配置

    <!-- 配置factoryBean的全類名,
    根據id:conn獲取到是Connection對象-->

    <bean id="conn" class="com.bcl.factory.ConnectionFactoryBean"/>

注意:

  • 根據id獲取到的複雜對象,不是FactoryBean
  • 能夠根據&id獲取到FactoryBean
  • 複雜對象的單例與否,只與isSingleton方法有關

3 Spring中對象的生命週期(瞭解)

生命週期: 從生到死的過程。

  1. 多例時 (scope="prototype")

    對象在getBean時建立
  2. 單例時(scope="singleton")

    對象在工廠建立時隨之建立
     初始化:init-method:對象建立後,執行1次方法
     銷燬:destroy-method:對象銷燬時,執行1次的方法
    對象在工廠關閉時銷燬

4 Spring配置文件分析

4.1 Spring配置文件的拆分

應用複雜時,須要將配置文件拆分紅多個小的配置文件,放置到不一樣模塊,最後在總配置文件中經過import標籤引入其它的小配置文件。

<import resource="classpath:a/applicationContext-a.xml"/>
<import resource="classpath:b/applicationContext-b.xml"/>

4.2 Spring 中xsd文件

xsd(XML Schema Definition)文件,規定了一個xml可使用哪些標籤、哪些屬性,以及它們的順序。

  1. xsd的基本使用

    image-20200601113429666

    使用xsd文件,要配置xsd的命名空間,以及文件路徑對。

  2. 在一個xml中使用多個xsd

    image-20200601114026438
  3. 示例:

    image-20200601120115361

4.3 Spring配置文件中拆分jdbc.properties

  1. 抽取jdbc.properties

    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/bcl2002?useUnicode=true&characterEncoding=utf8
    jdbc.username=root
    jdbc.password=root
  2. 讀取配置文件

    <context:property-placeholder location="classpath:jdbc.properties"/>
  3. 使用jdbc.properties中的參數

    <bean id="conn" class="com.bcl.factory.ConnectionFactoryBean">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

注意:${username} 會優先讀取操做系統用戶名,能夠給參數添加前綴進行區分。

5 Spring IOC和DI

IOC(Inversion Of Control)控制反轉 (思想)

DI(Dependency Injection)依賴注入 (實現手段)

控制:對於對象屬性賦值的控制權力。

image-20200601141742924

正向控制的問題:強耦合。

解決方案:控制反轉。

image-20200601142542072

結論:要解耦合,就不要new,轉爲在spring配置文件中經過配置的方式由工廠建立對象。

6 Spring整合Struts2

準備工做:建立好一個可運行的struts2項目。

6.1 整合效果

image-20200601152503882

Spring整合Struts2的效果:由Spring工廠建立Struts2須要的Action和Service.

6.2 實戰

導入spring-web 依賴

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.26.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-spring-plugin</artifactId>
    <version>2.3.16.3</version>
</dependency>
  1. tomcat啓動應用時,自動建立Spring工廠

    web.xml

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  2. Struts2從Spring工廠中獲取Action

    applicationContext.xml

    <bean id="userService" class="com.bcl.service.impl.UserServiceImpl"/>
    <bean id="userAction" class="com.bcl.action.UserAction" scope="prototype">
        <property name="userService" ref="userService"/>
    </bean>

    struts.xml

    <package name="day02" extends="struts-default" namespace="/day02">
        <!--
       class配置的是spring配置文件中Action的id
     -->

        <action name="showAllUsers" class="userAction" method="showAllUsers">
            <result name="success">/showAllUsers.jsp</result>
        </action>
    </package>

7 Spring整合JUnit

以前的JUnit測試Spring框架,每次都須要讀取配置文件,建立工廠,測試繁瑣。

解決方案:使用 spring-test 進行測試

準備工做:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.26.RELEASE</version>
</dependency>

簡化測試:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class ApplicationContextTest {
    @Autowired
    private User u;

    @Test
    public void testUser(){
        System.out.println("u = " + u);
    }
}

8 Spring基於註解的配置方式

使用註解替換xml配置的好處:簡化配置、提升開發效率。

註解的不足:不利於配置的管理。

8.1 使用註解的思路

image-20200601165433399

操做思路:

使用Component註解替換bean標籤配置

使用Autowired註解替換property標籤

8.2 註解開發的步驟

  1. 給類和屬性添加註解

    @Component("userService")
    public class UserServiceImpl implements UserService {
        ...
    }

    @Component("userAction")
    public class UserAction {
        @Autowired
        private UserService userService;

        public void setUserService(UserService userService) {
            this.userService = userService;
        }
        ...
    }
  2. 查找註解:配置查找註解的起始包名

    applicationContext.xml

    <!--
    <context:component-scan base-package="com.bcl.action,com.bcl.service.impl"/>-->

    <context:component-scan base-package="com.bcl"/>

8.3 核心註解

@Component

Component註解替換bean標籤,建立對象。與其做用相同還有3個註解:

@Controller 用在action層

@Service  用在service層

@Repository 用在dao層

注意事項:

  1. 後3個註解實際開發時使用頻率更高,比Component有更高的辨識度

  2. MyBatis框架中,Repository沒有使用場景

  3. 4個註解在使用時,均可以省略id參數。會有默認id:類名首字母小寫

    UserAction==> userAction    UserServiceImpl ==> userServiceImpl

@Autowired

用於屬性注入。

注意事項:

  1. 默認根據類型查找所須要的屬性對象
  2. Autowired 用於屬性上,底層經過反射操做屬性賦值
  3. Autowired用在set方法上,底層經過調用set方法賦值

@Qualifier

當Autowired注入屬性,Spring中有不止一個知足條件的對象,爲了分辨使用哪一個對象,能夠經過@Qualifier("bean的id") 肯定。

@Controller("userAction")
public class UserAction {
    @Autowired
    @Qualifier("userServiceImpl2")
    private UserService userService;
    ...
}

@Scope

決定是否單例。

@Controller("userAction")
@Scope("prototype")
public class UserAction {
    ...
}

業內標準:

  1. 對於自定義的類型,使用註解。好比:dao、service、action
  2. 第3方類型,使用xml。好比:數據庫鏈接池、事務管理器

「❤️ 帥氣的你又來看了我」

若是你以爲這篇內容對你挺有有幫助的話:

  1. 點贊支持下吧,讓更多的人也能看到這篇內容(收藏不點贊,都是耍流氓 -_-)

  2. 歡迎在留言區與我分享你的想法,也歡迎你在留言區記錄你的思考過程。

  3. 以爲不錯的話,也能夠關注 編程鹿 的我的公衆號看更多文章和講解視頻(感謝你們的鼓勵與支持🌹🌹🌹)


本文分享自微信公衆號 - 鹿小洋的Java筆記(lulaoshiJava)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索