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了。
各个属性都是对应的。

猜你喜欢

转载自blog.csdn.net/IPI715718/article/details/82701072
今日推荐