1. 程式人生 > 其它 >spring IOC 使用註解方式配置

spring IOC 使用註解方式配置

spring·基於註解的方式IOC操作bean管理

1 配置maven依賴

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.9.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>
</dependencies>

2 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"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    	<!--開啟元件掃描>
        <context:annotation-config/>
    
        <!--要寫的內容-->
       
    </beans>
    

    3 在要建立類的上面添加註解@component

    • @Component, @Service, @Controller, @Repository作用是一樣的
    • 註解裡面的value屬性值可以省略不寫

    • 預設值是類名稱,首字母小寫

      如:UserService -- userService

    • 在xml配置檔案上配置bean檔案

    4 元件掃描的細節

    • 在xml檔案配置

    • use-default-filter="false",表示不使用預設的filter,自己設定掃描內容

      <context:component-scan base-package="com.atguigu" use-defaultfilters="false">
       <context:include-filter type="annotation"
      
      expression="org.springframework.stereotype.Controller"/>
      </context:component-scan>
      
      

      意思是:在com.atguigu這個包中,預設不掃描,掃描型別是註解,註解是@Controller下的類

    • exclude-filter:設定那些內容不進行掃描

      <context:component-scan base-package="com.atguigu">
       <context:exclude-filter type="annotation"
      
      expression="org.springframework.stereotype.Controller"/>
      </context:component-scan>
      

    5 基於註解方式實現屬性注入

    1. @Autowired
    2. @Qualifier
    3. @Resource
    4. Value
    • @Autowired:根據屬性型別進行自動裝配

      操作步驟:1 用註解的方式建立物件

      2 在要實現屬性注入的物件上面新增@Autowire註解

    • @Qualifier:根據名稱進行注入

      @Qualifier(value = "屬性名稱")

    • @Resource:可以根據型別注入,可以根據名稱注入

6 完全註解開發

1 建立一個配置類

2 在類上面寫註解

@Configuration //作為配置類,替代 xml 配置檔案
@ComponentScan(basePackages = {"com.atguigu"})
public class SpringConfig {
}

3 建立測試類

將ClassPathXMLConfigApplication改寫程AnnotationConfigApplication

@Test
public void testService2() {
 //載入配置類
 ApplicationContext context
 = new AnnotationConfigApplicationContext(SpringConfig.class);
    
    
}