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配置写法:

<?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: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文件中的 “<beans></beans>” 标签;

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

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

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

Alt

提示
本人以抱着学习的态度去分享,以上内容如有雷同,不胜荣幸!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring XML配置是一种传统的配置方式,用于配置Spring框架中的Bean和它们之间的依赖关系。通过XML配置文件,我们可以定义和组织应用程序中的各个组件,包括Bean的定义、Bean之间的关系、AOP配置、数据源配置等。 在Spring XML配置中,通常会使用以下几个核心元素进行配置: 1. `<beans>`:作为根元素,用于定义整个配置文件的作用域。 2. `<bean>`:用于定义一个Bean,包括Bean的ID、名、作用域等属性。 3. `<property>`:用于设置Bean的属性值,可以通过`name`属性指定属性名,或直接使用内联方式设置属性值。 4. `<constructor-arg>`:用于设置Bean的构造函数参数,可以通过`index`或`type`属性指定参数位置或型。 5. `<import>`:用于导入其他XML配置文件。 6. `<alias>`:用于定义Bean的别名。 7. `<bean>`和`<property>`等元素还可以使用一些命名空间来简化配置,如`<context:component-scan>`用于自动扫描组件等。 除了以上核心元素外,Spring XML配置还支持一些其他的元素和属性,如AOP相关的配置、事务管理配置等。需要根据具体的需求和场景来灵活使用和配置。 需要注意的是,随着Spring框架的发展,基于Java配置的方式(如使用注解和Java进行配置)逐渐取代了XML配置方式,因为它更加简洁、型安全,并且易于维护。但对于一些遗留的项目和特殊的需求,XML配置仍然是一种常用的配置方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值