Spring Xml配置与Spring配置类配置比较

Spring Xml配置与Spring配置类配置比较

这里用的是Shiro的Web过滤器配置类如下:

package com.jhkj.management.common.shiro;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfiguration {
    @Value("${redis.host}")
    private String redisHost;

    @Value("${redis.password}")
    private String redisPwd;

    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        
        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //拦截器
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(8);
        filterChainDefinitionMap.put("/webjars/**", "anon");
        filterChainDefinitionMap.put("/ins/manage/logout", "logout");
        filterChainDefinitionMap.put("/unauth", "anon");//anon 可以理解为不拦截
        filterChainDefinitionMap.put("/captcha/**", "anon");//anon 可以理解为不拦截
        filterChainDefinitionMap.put("/ins/manage/unAuth", "anon");
        filterChainDefinitionMap.put("/ins/manage/toLogin", "anon");
        filterChainDefinitionMap.put("/ins/manage/userLogin", "anon");
        filterChainDefinitionMap.put("/ins/manage/logout", "anon");
        filterChainDefinitionMap.put("/reissue/**", "anon");
        filterChainDefinitionMap.put("/cargo/commonOrder/**", "anon");    //志愿汇众惠HTML不拦截
        filterChainDefinitionMap.put("/cargo/obtainnoworries/**", "anon");   //你我校html不拦截
        filterChainDefinitionMap.put("/cargo/chilePush/**", "anon");   //儿推场馆html不拦截
        filterChainDefinitionMap.put("/website/**", "anon");
        filterChainDefinitionMap.put("/cargo/queryVolAss", "anon");
        filterChainDefinitionMap.put("/**", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        shiroFilterFactoryBean.setLoginUrl("/ins/manage/toLogin");
        shiroFilterFactoryBean.setUnauthorizedUrl("/ins/manage/unAuth");
        return shiroFilterFactoryBean;
    }
    
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userShiroRealm());
        //注入记住我管理器
        securityManager.setRememberMeManager(rememberMeManager());
        // 自定义session管理 使用redis
        securityManager.setSessionManager(sessionManager());
        // 自定义缓存实现 使用redis
        securityManager.setCacheManager(cacheManager());
        return securityManager;
    }
    
    
    /**
     * 自定义sessionManager
     *
     * @return
     */
    @Bean
    public SessionManager sessionManager() {
        MySessionManager mySessionManager = new MySessionManager();
        mySessionManager.setSessionDAO(redisSessionDAO());
        return mySessionManager;
    }
    
    
    /**
     * 身份认证realm
     * (这个需要自己写,账号密码校验;权限等)
     *
     * @return
     */
    @Bean
    public UserShiroRealm userShiroRealm() {
        UserShiroRealm userShiroRealm = new UserShiroRealm();
        userShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return userShiroRealm;
    }
    
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //散列算法:这里使用MD5算法;
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        //散列的次数,比如散列两次,相当于 md5(md5(""))
        hashedCredentialsMatcher.setHashIterations(1);
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }
    
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
    
    @Bean
    public SimpleCookie rememberMeCookie() {
        //这个参数是cookie的名称,对应前端的checkbox的name = rememberMe
        SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
        // 记住我cookie生效时间30天 ,单位秒
        simpleCookie.setMaxAge(100000);
        return simpleCookie;
    }
    
    /**
     * cookie管理对象
     *
     * @return
     */
    @Bean
    public CookieRememberMeManager rememberMeManager() {
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());
        return cookieRememberMeManager;
        
    }
    
    /**
     * RedisSessionDAO shiro sessionDao层的实现 通过redis
     * 使用的是shiro-redis开源插件
     */
    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }
    
    /**
     * 配置shiro redisManager
     * 使用的是shiro-redis开源插件
     * 需要设置此处的redis信息
     *
     * @return
     */
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
//        redisManager.setHost("127.0.0.1");
        redisManager.setHost(redisHost);
        redisManager.setPort(6379);
        redisManager.setPassword(redisPwd);
        // 配置缓存过期时间
        redisManager.setExpire(3600);
        redisManager.setTimeout(100000);
        return redisManager;
    }
    
    /**
     * cacheManager 缓存 redis实现
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    @Bean
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        return redisCacheManager;
    }
}

下面是Spring的xml配置写法:


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">


	<bean id="shiroFilterFactoryBean" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="filterChainDefinitionMap">
            <map>
                <entry key="/webjars/**" value="anon"/>
                <entry key="/ins/manage/logout" value="logout"/>
                <entry key="/unauth" value="anon"/>
                <entry key="/captcha/**" value="anon"/>
                <entry key="/ins/manage/unAuth" value="anon"/>
                <entry key="/ins/manage/toLogin" value=""/>
                <entry key="/ins/manage/userLogin" value="anon"/>
                <entry key="/ins/manage/logout" value="anon"/>
                <entry key="/reissue/**" value="anon"/>
                <entry key="/cargo/commonOrder/**" value="anon"/>
                <entry key="/cargo/obtainnoworries/**" value="anon"/>
                <entry key="/cargo/chilePush/**" value="anon"/>
                <entry key="/cargo/queryVolAss" value="anon"/>
                <entry key="/website/**" value="anon"/>
                <entry key="/**" value="authc"/>
            map>
        property>
        <property name="loginUrl" value="/ins/manage/toLogin"/>
        <property name="unauthorizedUrl" value="/ins/manage/unAuth"/>
    bean>


    <bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">
        <property name="realm" ref="userShiroRealm"/>
        <property name="rememberMeManager" ref="rememberMeManager"/>
        <property name="sessionManager" ref="sessionManager"/>
        <property name="cacheManager" ref="cacheManager"/>
    bean>

    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <property name="cookie" ref="simpleCookie"/>
    bean>

    <bean id="simpleCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <property name="maxAge" value="100000"/>
    bean>

    <bean id="userShiroRealm" class="com.jhkj.management.common.shiro.UserShiroRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
    bean>

    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <property name="hashAlgorithmName" value="md5"/>
        <property name="hashIterations" value="1"/>
        <property name="StoredCredentialsHexEncoded" value="true"/>
    bean>
    <bean id="sessionManager" class="com.jhkj.management.common.shiro.MySessionManager">
        <property name="sessionDAO" ref="redisSessionDAO"/>
    bean>


    <bean id="redisSessionDAO" class="org.crazycake.shiro.RedisSessionDAO">
        <property name="redisManager" ref="redisManager"/>
    bean>

    <bean id="redisManager" class="org.crazycake.shiro.RedisManager">
        <property name="host" value="127.0.0.1"/>
        <property name="port" value="6379"/>
        <property name="password" value="jhtech"/>
        <property name="expire" value="3600"/>
        <property name="timeout" value="100000"/>
    bean>

    <bean id="cacheManager" class="org.crazycake.shiro.RedisCacheManager">
        <property name="redisManager" ref="redisManager"/>
    bean>

beans>

以上两片代码实现的功能是完全相同的,一个是配置类利用@Configuration 和 @Bean注解完成的,而另一种是以前常用的XML方式(多用于以前的老框架例如:Spring MVC+Spring+Mybatis…)来实现的。但是老框架也是可以用这些注解扫描进行实现,在这里只是对写法上做一个对比。又多了一种写法不是吗?

(1)@Configuration:修饰一个java配置类,相当于Spring xml文件中的 “” 标签;

(2)@Bean:注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个 Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中

(3)@Value:修饰一个字段,配置变量

(4)@Import:修饰配置类,用于当前java配置类中导入其他配置类

Alt

提示
本人以抱着学习的态度去分享,以上内容如有雷同,不胜荣幸!

你可能感兴趣的:(开源框架,框架小知识,spring)