0、寫在前面的話
一直想能仿公司框架的形式,着手作一個簡單的腳手架,一來是帶着目標性能更好地學習,接觸新的技術,另外本身若是有什麼想要實現的簡單需求,就能夠進行快速開發,主要仍是但願能在權限上有所控制,因此最花時間的仍是在Shiro上。
其實目標在github已經有很多大佬的參考物了:
- zheng 基於Spring+SpringMVC+Mybatis分佈式敏捷開發系統架構,提供整套公共微服務服務模塊
- ES JavaEE企業級項目的快速開發的腳手架,提供了底層抽象和通用功能,拿來即用
- renren-security 輕量級權限管理系統
- lenos 快速開發模塊化腳手架
我本身也試着搭建了最簡單的包含權限的後端,主要是爲了走通整個流程,以後也會慢慢試着參考大佬們作一款本身的架子。在整個集成過程當中,固然難免遇到了各類奇奇怪怪的問題,這裏作一些簡單的經驗記錄,避免舊坑重踩。
一、技術框架整合
1.1 Maven多模塊項目的搭建
參考連接:
1.2 SpringBoot-MyBatis集成
參考連接:
1.3 SpringBoot-Shiro集成
參考連接:
二、踩坑警告
- SpringBoot 版本:2.0.3.RELEASE
- JUnit 版本:4.12
- SpringBoot-MyBatis 版本:1.3.2
- SpringBoot-Shiro 版本:1.4.0-RC2
2.1 多模塊帶來的注意事項
SpringBoot 多模塊的單元測試須要指定註解 @SpringBootTest(classes = {Application.class}),這裏的 Application.class 即你的SpringBoot啓動類,這也就意味着你其餘模塊的測試也只能在 Application.class 所在的模塊中進行,不然編譯沒法經過由於其餘模塊找不到 Application.class,固然這是由於其餘模塊中的依賴問題致使的。
另外須要注意的是,SpringBoot中 的 Bean 掃描默認爲 Application.java 所在包及子包,因此哪怕是多模塊,也請注意包名的問題,並調整 Application.java 的位置,不然很容易出現找不到 Bean 注入的狀況。
若是你還使用了 MyBatis-generator,一樣其對於數據源的配置文件,由於多模塊的緣故,你可能也沒法直接使用 SpringBoot 中 application.properties 的配置,須要單獨寫一個配置文件在 MyBatis-generator 使用的那個模塊下。
2.2 SpringBoot+MyBatis與單元測試
若是在單元測試時發現 xxxMapper 或 xxxDao 的 Bean 沒法注入,那麼請注意你使用的註解了。在持久層接口上註解使用 @Mapper,而不是僅僅使用 @Repository。實際上哪怕不使用 @Repository 也能夠注入持久層的 Bean,可是IDE會在Service類中報紅提醒 xxxDao 沒有註冊 Bean,因此最好仍是加上 @Repository,儘管去掉也沒有什麼影響。
@Repository
@Mapper
public interface RoleDao {
int deleteByPrimaryKey(Long id);
int insert(Role record);
int insertSelective(Role record);
Role selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Role record);
int updateByPrimaryKey(Role record);
Set<Role> findAll();
Set<Role> findByUserId(Long userId);
}
2.3 Shiro中自定義Realm的Bean註冊
在 SpringBoot 和 Shiro 的集成中,Shiro的配置一般是使用一個自定義配置類,經過在方法上使用 @Bean 註解來將配置註冊成 Bean,以下:
@Configuration
public class ShiroConfig {
@Bean
public Realm realm() {
return new MyRealm();
}
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition chain = new DefaultShiroFilterChainDefinition();
//todo "/anon" not useful
chain.addPathDefinition("/anon/*", "anon");
chain.addPathDefinition("/authc/*", "authc");
return chain;
}
}
那麼在自定義的Realm中還須要單獨的註解(如 @Component)標記嗎?答案是不須要。以下,哪怕它之中還須要用到其餘的 Bean 組件,也不須要再單獨作組件註解了(加上反而由於和 @Bean 的方式衝突報錯):
//無需 @Component
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//...
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//...
return null;
}
}
另外須要注意的是,在配置url訪問權限時,以下兩種寫法請注意:
- chain.addPathDefinition("/anon", "anon"); //無效
- chain.addPathDefinition("/anon/*", "anon"); //有效
三、Demo源碼