【Spring】(4)IoC - 基於註解的容器配置

一、基於註解的容器配置

之前Spring容器一直使用xml配置,現在終於到註解了。畢竟如果一直使用xml配置,類多了配置起來就難受了。

這篇文章開始,使用註解,會非常開心。對以後學習SpringBoot幫助也很大。

注意:這裏並不是說xml配置不好,兩者各有優缺點,註解和xml的選擇需要看情況而定。

1.準備

要使用註解開發,必須要保證aop的包導入了!

並且配置文件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:context="http://www.springframework.org/schema/context"
       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">
   
    <!-- 掃描com.shengjava包下的所有註解 -->
    <context:component-scan base-package="com.shengjava"/>

</beans>  

2.代碼

項目結構:

在這裏插入圖片描述
User類。使用了註解 @Component、@Scope、@Value

/**
 * 註解@Component等價於:<bean id="user" class="com.shengjava.pojo.User"/>
 * 該註解會將下面的User類創建對象,命名爲小駝峯格式user,並把該對象交給Spring容器ApplicationContext進行管理。
 * 註解@Scope("prototype")等價於:在<bean id="user" class="com.shengjava.pojo.User" scope="prototype"/>中,加了一個 scope="prototype";
 */
@Component
@Scope("prototype")
public class User {
    /**
     *  註解@Value("長生2")等價於:<property name="name" value="長生2"></property>
     *  可以放到set方法上,也可以放到字段上。如果兩者都有值,則優先取set方法上的。
     */
    @Value("長生2")
    private String name;

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
    public String getName() {
        return name;
    }
    /**
     * 註解@Value("中國浙江")等價於:<property name="address" value="中國浙江"></property>
     */
    @Value("長生")
    public void setName(String name) {
        this.name = name;
    }
}

UserController類。使用了註解 @Controller

/**
 * 註解@Controller語義爲控制器,常用於放在控制跳轉的類上,作用和@Component一樣。
 */
@Controller
public class UserController {
    /**
     * 自動裝配註解@Autowired(放在屬性字段上)。通過byType的方式實現。
     * 等價於:<bean id="userService" class="com.shengjava.dao.UserController" autowire="byType"></bean>
     */
    @Autowired
    private UserService userService;
}

UserService類。使用了註解 @Service、@Autowired

/**
 * 註解@Service語義爲服務,常用於放在業務服務的類上,作用和@Component一樣。
 */
@Service
public class UserService {
    /**
     * 自動裝配註解@Autowired(放在屬性字段上)。通過byType的方式實現。
     * 等價於:<bean id="userDao" class="com.shengjava.dao.UserDao" autowire="byType"></bean>
     */
    @Autowired
    private UserDao userDao;
}

UserDao類。使用了註解 @Repository

/**
 * 註解@Repository語義爲倉庫,常用於放在數據訪問的類上,作用和@Component一樣。
 */
@Repository
public class UserDao {
}

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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 掃描com.shengjava包下的所有註解 -->
    <context:component-scan base-package="com.shengjava"/>

</beans>

測試類

public class AnnotationTest {
    public static void main(String[] args) {
        // 獲取xml配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 獲取對象
        User user = context.getBean("user", User.class);
        UserController userController = context.getBean("userController", UserController.class);
        UserService userService = context.getBean("userService", UserService.class);
        UserDao userDao = context.getBean("userDao", UserDao.class);
        // 輸出
        System.out.println(user);
        System.out.println(userController);
        System.out.println(userService);
        System.out.println(userDao);
    }
}

輸出

User{name='長生'}
com.shengjava.controller.UserController@3e96bacf
com.shengjava.service.UserService@484970b0
com.shengjava.dao.UserDao@4470f8a6

3.註解總結

3.1 bean註解 @Component、@Controller、@Service 和 @Repository

@Component 註解衍生出了其他幾個功能一模一樣的註解,只是單詞不一樣而已。
如:@Controller、@Service、@Repository。

這三個對應我們的web開發時候的MVC三層架構分層。

  • 控制層(controller層):使用 @Controller 註解。
  • 業務服務層(service層):使用 @Repository 註解。
  • 數據訪問層(dao層):則使用 @Repository 註解。
  • 組件:使用 @Component 註解。

這四個註解會將類創建對象,命名爲小駝峯格式user,並把該對象交給Spring容器ApplicationContext進行管理。

例如,User類上面的@Component註解等價於下面這段xml配置:

<bean id="user" class="com.shengjava.pojo.User"/>
3.2 自動裝配註解 @Autowired

自動裝配註解@Autowired(放在屬性字段上)。通過byType的方式實現。

例如,UserController 類 userService 屬性上的@Autowired,等價於下面這段xml配置:

<bean id="userService" class="com.shengjava.dao.UserController" autowire="byType"></bean>

你也可以使用註解 @Resouce 註解,作用和 @Autowired 一樣,不過是先用過byName,如果byName沒找到,再使用byType。

3.3 bean的作用域註解 @Scope

例如,User類上的註解@Scope(“prototype”)等價於下面這段xml:

<bean id="user" class="com.shengjava.pojo.User" scope="prototype"/>
3.4 @Value

@Value 通常用於注入外部屬性。詳情:1.9.8. Using @Value

例如,User類name屬性上的註解@Value(“長生2”)等價於如下xml:

@Value可以放到set方法上,也可以放到字段上。如果兩者都有值,則優先取set方法上的。

<property name="name" value="長生2"></property>

參考自:1.9. Annotation-based Container Configuration


相關

我的該分類的其他相關文章,請點擊:【Spring】文章目錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章