1. 程式人生 > >Springboot中的@Configuration和@Bean

Springboot中的@Configuration和@Bean

問題的提出:springboot 的properties已經包含了很多預設配置了 我們再用@Configuration 配置的目的是什麼 ?

問題回答:在Spring Boot中,Starter為我們自動啟用了很多Bean,這些Bean的配置資訊通過properties的方式暴露出來以供使用人員調整引數,但並不是通過調整properties檔案能配置所有的Bean,一下負責的Bean配置還是需要使用@Configuration方式,比如Spring Security的WebSecurityConfigurerAdapter配置。

@Configuration註解可以達到在Spring中使用xml配置檔案的作用。

@Bean就等同於xml配置檔案中的<bean>

1、第一種自己寫的類,Controller,Service。 用@controller @service即可

2、第二種,整合其它框架,比如整合shiro許可權框架,整合mybatis分頁外掛PageHelper,第三方框架的核心類都要交於Spring大管家管理

@Configuration可理解為用spring的時候xml裡面的<beans>標籤

@Bean可理解為用spring的時候xml裡面的<bean>標籤

Spring Boot不是spring的加強版,所以@Configuration和@Bean同樣可以用在普通的spring專案中,而不是Spring Boot特有的,只是在spring用的時候,注意加上掃包配置

<context:component-scan base-package="com.xxx.xxx" />,普通的spring專案好多註解都需要掃包,才有用,有時候自己註解用的挺6,但不起效果,就要注意這點。

Spring Boot則不需要,主要你保證你的啟動Spring Boot main入口,在這些類的上層包就行。

舉例說明:

在普通的Spring配置檔案中,需要引入spring-content-shiro.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-4.0.xsd
        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.0.xsd"
    default-lazy-init="true">

   <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
       <!-- session的失效時長,單位毫秒 -->
     <property name="globalSessionTimeout" value="600000"/>
      <!-- 刪除失效的session -->
     <property name="deleteInvalidSessions" value="true"/>
   </bean>
</beans>  

在Springboot裡 只需要註解類名和方法名

@Configuration
public class ShiroConfig {
    @Bean("sessionManager")
    public SessionManager sessionManager(){
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setGlobalSessionTimeout(600000);
        sessionManager.setDeleteInvalidSessions(true);
        return sessionManager;
    }
}

在bean中的class = “org.apache.shiro.web.session.mgt.DefaultWebSessionManager” 應該就是在java程式碼裡返回的那個SessionManager了。
各個屬性都是對應的。