1. 程式人生 > 實用技巧 >Spring-IoC-DI-基於註解方式的依賴注入(案例一:簡單物件建立)

Spring-IoC-DI-基於註解方式的依賴注入(案例一:簡單物件建立)

1.什麼是註解

(1)註解是程式碼特殊標記,格式:@註解名稱(屬性名稱=屬性值,屬性名稱=屬性值…)

(2)使用註解,註解作用在類上面,方法上面,屬性上面

(3)使用註解的目的:簡化XML配置

2.Spring針對Bean管理中建立物件提供註解

(1)@Component:普通的元件,都可

(2)@Service::一般用在業務邏輯層或service層

(3)@Controller::一般用在web層

(4)@repository:一般用在dao層

上面四個註解功能是一樣的,都可以用來建立bean例項

3.基於註解方式實現物件建立

(1)建立類,使用註解

package com.orzjiangxiaoyu.spring.test1;

import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; /** * @author orz * @create 2020-08-16 17:27 */ //註解裡面value屬性值可以省略不寫 //預設值是類名稱,首字母小寫 //UserService-userService @Service(value = "userService") //<bean id="userService" class="..."></bean> public class UserService {
public void add() { System.out.println("service add ..."); } }

(2)配置bean檔案

①匯入spring對應AOP的jar包,安裝依賴(spring-aop-5.2.6.RELEASE.jar)

②建立bean.xml檔案,配置context名字空間

<?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:p
="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 開始元件掃面 --> <!-- 1.如果掃描多個包,多個包使用逗號隔開 2.掃描包上層目錄 --> <context:component-scan base-package="com.orzjiangxiaoyu.spring.test1"></context:component-scan> </beans>

(3)測試

package com.orzjiangxiaoyu.spring.test1;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @author orz
 * @create 2020-08-16 17:06
 */
public class Test1 {
    @Test
    public void test1()
    {
        //1.載入spring配置檔案
        ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
        //2.獲取配置檔案的建立物件
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();

    }
}

(4)結果

service add ...