springBoot整合shiro如何解决读取不到@value值问题

 更新时间:2023年08月25日 09:23:10   作者:hzau_itdog  
这篇文章主要介绍了springBoot整合shiro如何解决读取不到@value值问题,具有很好的参考价值,希望对大家有所帮助,

springBoot整合shiro读取不到@value值

1、通过@value将值注入shiroconfigure静态属性

    private static String dropmenu_post;
	@Value("${dropmenu.post}")
	public void setDropmenu_post(String dropmenu_post) {
		ShiroConfig.dropmenu_post = dropmenu_post;
	}

2、将LifecycleBeanPostProcessor获取该对象的方法设为静态

    @Bean
	public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
		return new LifecycleBeanPostProcessor();
	}

 3、使用

@Bean(name = "shiroFilter")
	public ShiroFilterFactoryBean getShiroFilterFactoryBean(
			@Qualifier("securityManager") SecurityManager securityManager) {
		ShiroFilterFactoryBean sfb = new ShiroFilterFactoryBean();
		sfb.setSecurityManager(securityManager);
		sfb.setLoginUrl(ShiroConfig.dropmenu_post + "/login");
		sfb.setSuccessUrl("/report/list");
		sfb.setUnauthorizedUrl("/goLogin");
		Map<String, Filter> filters = new HashMap<>();
		filters.put("per", getPermissionFilter());
		// filters.put("verCode",getVerfityCodeFilter());
		sfb.setFilters(filters);
		Map<String, String> filterMap = new LinkedHashMap<>();
		filterMap.put("/resources/**", "anon");
		filterMap.put("/fx/**", "anon");
		filterMap.put("/fx2/**", "anon");
		filterMap.put("/process/**", "anon");
		filterMap.put("/repeat/**", "anon");
		filterMap.put("/repeat2/**", "anon");
		filterMap.put("/ipad/**", "anon");
		filterMap.put("/student/**", "anon");
		filterMap.put("/excel/**", "anon");
		filterMap.put("/exam/**", "anon");
		filterMap.put("/progress/**", "anon");
		filterMap.put("/param/**", "anon");
		filterMap.put("/statics/**", "anon");
		filterMap.put("/download/**", "anon");
		filterMap.put("/knowledge/**", "anon");
		filterMap.put("/login", "anon");
		filterMap.put("/actuator/**", "anon");
		filterMap.put("/hystrix", "anon");
		filterMap.put("/hystrix.stream", "anon");
		filterMap.put("/logout", "logout");
		filterMap.put("/js/**", "anon");
		filterMap.put("/css/**", "anon");
		filterMap.put("/user/**", "per");
		filterMap.put("/**", "authc");
		sfb.setFilterChainDefinitionMap(filterMap);
		return sfb;
	}

整个类的代码如下 

package com.whty.hxx.config;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.Filter;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;
import com.whty.hxx.common.filter.PermissionFilter;
import com.whty.hxx.common.shiro.LoginRealm;
import com.whty.hxx.common.shiro.MyWebSessionManager;
import com.whty.hxx.common.shiro.ShiroUtil;
import com.whty.hxx.common.shiro.redis.RedisSessionDAO;
import com.whty.hxx.common.shiro.redis.ShiroRedisCacheManager;
import lombok.extern.slf4j.Slf4j;
/**
 * @author yym
 * @date 2018/5/31. spring shiro 配置
 */
@Configuration
@Slf4j
public class ShiroConfig {
	private static String dropmenu_post;
	@Value("${dropmenu.post}")
	public void setDropmenu_post(String dropmenu_post) {
		ShiroConfig.dropmenu_post = dropmenu_post;
	}
	@Bean(value = "ehCacheManager")
	public EhCacheManager ehCacheManager() {
		EhCacheManager ehCacheManager = new EhCacheManager();
		ehCacheManager.setCacheManagerConfigFile("classpath:ehcache/ehcache.xml");
		return ehCacheManager;
	}
	// @Bean(name="credentialsMatcher")
	// public RetryLimitCredentialsMatcher
	// getRetryLimitCredentialsMatcher(@Qualifier("redisCacheManager")
	// ShiroSpringCacheManager redisCacheManager){
	 RetryLimitCredentialsMatcher rm = new
	// RetryLimitCredentialsMatcher(getCacheManager(),2);
	// RetryLimitCredentialsMatcher rm = new
	// RetryLimitCredentialsMatcher(redisCacheManager);
	// rm.setHashAlgorithmName("md5");
	// rm.setHashIterations(4);
	// return rm;
	//
	// }
	// @Bean(name = "redisCacheManager")
	// public ShiroRedisCacheManager redisCacheManager() {
	// log.debug("ShiroConfiguration.redisCacheManager()");
	// return new ShiroRedisCacheManager();
	// }
	@Bean(name = "redisSessionDAO")
	public RedisSessionDAO redisSessionDAO() {
		log.debug("ShiroConfiguration.redisSessionDAO()");
		return new RedisSessionDAO();
	}
	@Bean(name = "loginRealm")
	public LoginRealm getLoginRealm(@Qualifier("redisCacheManager") ShiroRedisCacheManager redisCacheManager) {
		LoginRealm realm = new LoginRealm();
		// 密码匹配校验�?
		HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
		credentialsMatcher.setHashAlgorithmName("md5");
		credentialsMatcher.setHashIterations(4);
		realm.setCredentialsMatcher(credentialsMatcher);
		realm.setCacheManager(redisCacheManager);
		// realm.setCachingEnabled(true);
		return realm;
	}
	@Bean
	public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
		return new LifecycleBeanPostProcessor();
	}
	// /**
	// *
	// * enterCacheSessionDAO:(EnterpriseCacheSessionDAO shiro sessionDao层的实现�?).
	// <br/>
	// * 提供了缓存功能的会话维护,默认情况下使用MapCache实现,内部使用ConcurrentHashMap保存缓存的会话�??.<br/>
	// *
	// * @author verywell
	// * @return
	// * @since JDK 1.8
	// */
	// @Bean(name="redisCacheSessionDAO")
	// public RedisSessionDao
	// getEnterCacheSessionDAO(@Qualifier("redisCacheManager")
	// ShiroSpringCacheManager redisCacheManager) {
	// RedisSessionDao enterCacheSessionDAO = new RedisSessionDao();
	// //添加缓存管理�?
	// enterCacheSessionDAO.setCacheManager(redisCacheManager);
	 添加ehcache活跃缓存名称(必须和ehcache缓存名称�?致)
	 enterCacheSessionDAO.setActiveSessionsCacheName("shiro-activeSessionCache");
	// return enterCacheSessionDAO;
	// }
	// @Bean(name="sessionValidationScheduler")
	// public MyQuartzSessionValidationScheduler
	// getQuartzSessionValidationScheduler(@Qualifier("redisSessionDAO")RedisSessionDAO
	// sessionDAO
	// ,@Qualifier("redisCacheManager") ShiroRedisCacheManager redisCacheManager) {
	// MyQuartzSessionValidationScheduler sessionValidationScheduler = new
	// MyQuartzSessionValidationScheduler();
	// sessionValidationScheduler.setSessionValidationInterval(10000);
	// DefaultWebSessionManager sessionManager=new DefaultWebSessionManager();
	// sessionManager.setCacheManager(redisCacheManager);
	// sessionManager.setSessionDAO(sessionDAO);
	// sessionValidationScheduler.setSessionManager(sessionManager);
	// return sessionValidationScheduler;
	// }
	@Bean(name = "sessionManager")
	public DefaultWebSessionManager getSessionManager(@Qualifier("redisSessionDAO") RedisSessionDAO sessionDAO,
			@Qualifier("redisCacheManager") ShiroRedisCacheManager cacheManager) {
		MyWebSessionManager sessionManager = new MyWebSessionManager();
		sessionManager.setSessionIdUrlRewritingEnabled(false);// sessionId不显示在url�?
		sessionManager.setCacheManager(cacheManager);
		sessionManager.setSessionDAO(sessionDAO);
		// sessionManager.setGlobalSessionTimeout(2000);
		// sessionManager.setSessionValidationScheduler(sessionValidationScheduler);
		// sessionManager.setSessionValidationInterval(3000);
		// 创建会话Cookie
		Cookie cookie = new SimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME);
		cookie.setName(ShiroUtil.name_serssionId);
		cookie.setHttpOnly(true);
		sessionManager.setSessionIdCookie(cookie);
		return sessionManager;
	}
	@Bean(name = "securityManager")
	public SecurityManager getSecurityManager(@Qualifier("loginRealm") LoginRealm loginRealm,
			@Qualifier("sessionManager") DefaultWebSessionManager sessionManager,
			@Qualifier("redisCacheManager") ShiroRedisCacheManager cacheManager) {
		DefaultWebSecurityManager dwm = new DefaultWebSecurityManager();
		dwm.setRealm(loginRealm);
		// dwm.setCacheManager(cacheManager);
		dwm.setSessionManager(sessionManager);
		return dwm;
	}
	@Bean
	public PermissionFilter getPermissionFilter() {
		PermissionFilter pf = new PermissionFilter();
		return pf;
	}
	// @Bean
	// public VerfityCodeFilter getVerfityCodeFilter(){
	// VerfityCodeFilter vf= new VerfityCodeFilter();
	// vf.setFailureKeyAttribute("shiroLoginFailure");
	// vf.setJcaptchaParam("code");
	// vf.setVerfitiCode(true);
	// return vf;
	// }
	@Bean(name = "shiroFilter")
	public ShiroFilterFactoryBean getShiroFilterFactoryBean(
			@Qualifier("securityManager") SecurityManager securityManager) {
		ShiroFilterFactoryBean sfb = new ShiroFilterFactoryBean();
		sfb.setSecurityManager(securityManager);
		sfb.setLoginUrl(ShiroConfig.dropmenu_post + "/login");
		sfb.setSuccessUrl("/report/list");
		sfb.setUnauthorizedUrl("/goLogin");
		Map<String, Filter> filters = new HashMap<>();
		filters.put("per", getPermissionFilter());
		// filters.put("verCode",getVerfityCodeFilter());
		sfb.setFilters(filters);
		Map<String, String> filterMap = new LinkedHashMap<>();
		filterMap.put("/resources/**", "anon");
		filterMap.put("/fx/**", "anon");
		filterMap.put("/fx2/**", "anon");
		filterMap.put("/process/**", "anon");
		filterMap.put("/repeat/**", "anon");
		filterMap.put("/repeat2/**", "anon");
		filterMap.put("/ipad/**", "anon");
		filterMap.put("/student/**", "anon");
		filterMap.put("/excel/**", "anon");
		filterMap.put("/exam/**", "anon");
		filterMap.put("/progress/**", "anon");
		filterMap.put("/param/**", "anon");
		filterMap.put("/statics/**", "anon");
		filterMap.put("/download/**", "anon");
		filterMap.put("/knowledge/**", "anon");
		// //===== 测试
		// filterMap.put("/test/**","anon");
		// filterMap.put("/report/**","anon");
		// filterMap.put("/upload/**","anon");
		// filterMap.put("/city/**","anon");
		// filterMap.put("/county/**","anon");
		// filterMap.put("/unitSchool/**","anon");
		// filterMap.put("/regionSchool/**","anon");
		// filterMap.put("/school/**","anon");
		// filterMap.put("/clazz/**","anon");
		// filterMap.put("/clazzEvaluation/**","anon");
		// filterMap.put("/schoolEvaluation/**","anon");
		// filterMap.put("/canvas/**","anon");
		// //===== end
		filterMap.put("/login", "anon");
		filterMap.put("/actuator/**", "anon");
		filterMap.put("/hystrix", "anon");
		filterMap.put("/hystrix.stream", "anon");
		filterMap.put("/logout", "logout");
		filterMap.put("/js/**", "anon");
		filterMap.put("/css/**", "anon");
		filterMap.put("/user/**", "per");
		filterMap.put("/**", "authc");
		sfb.setFilterChainDefinitionMap(filterMap);
		return sfb;
	}
	@Bean
	public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
		DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
		advisorAutoProxyCreator.setProxyTargetClass(true);
		return advisorAutoProxyCreator;
	}
	@Bean
	public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(
			@Qualifier("securityManager") SecurityManager securityManager) {
		AuthorizationAttributeSourceAdvisor as = new AuthorizationAttributeSourceAdvisor();
		as.setSecurityManager(securityManager);
		return as;
	}
	@Bean
	public FilterRegistrationBean delegatingFilterProxy() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		DelegatingFilterProxy proxy = new DelegatingFilterProxy();
		proxy.setTargetFilterLifecycle(true);
		proxy.setTargetBeanName("shiroFilter");
		filterRegistrationBean.setFilter(proxy);
		return filterRegistrationBean;
	}
}

springboot单元测试使用@value读取不到值, yml的两个坑

yml两个坑

yml 和 properties都可以作为配置文件在springboot项目中使用

缩进问题

yml使用空格缩进代表包之间的层级问题,有时候差一个空格就可能导致配置不生效。另外,在同级配置之间使用 # 注释

也会导致该问题,因为程序是按层级读取配置的,加上注释隔断上下两行之后,程序会不清楚下一条配置是上一个的下级还是同级(大致是这意思。。。)

springboot 2.X版本在单元测试中读取不到yml配置文件的值

这是个大坑,在项目中写单元测试的时候需要读取一个yml配置文件的值,发现无论如何都读取不到,后来发现了这个坑。改成properties就行了。

总结

建议用properties!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

最新评论