Is there any old springmvc project? If you want to convert it to a springboot project, just read this article.
illustrate
If your project is not even a maven project, please convert it to a maven project by yourself and follow this tutorial.
This tutorial is suitable for the maven project of spring+springmvc+mybatis+shiro.
1. Modify the pom file dependency
Delete the previous spring dependency and add springboot dependency
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version></parent><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- This is to remove the built-in tomcat deployment --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusions> </dependency> <!-- tomcat container deployment --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <!--<scope>compile</scope>--> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!-- Support @ConfigurationProperties annotation--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency></dependencies>
Add springboot build plugin
<plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>1.5.9.RELEASE</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin></plugins>
2. Add application startup file
Note that if the Application is in the previous layer package of controller, service, and dao, there is no need to configure @ComponentScan,
Otherwise, you need to specify which package to scan.
@SpringBootApplication//@ComponentScan({"com.cms.controller","com.cms.service","com.cms.dao"})public class Applicationextends SpringBootServletInitializer{ @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application){ return application.sources(Application.class); } public static void main(String[] args)throws Exception { SpringApplication.run(Application.class, args); }}3. Add springboot configuration file
Add application.properties file under resources
Add basic configuration #Default prefix server.contextPath=/# Specify environment spring.profiles.active=local# jsp configuration spring.mvc.view.prefix=/WEB-INF/jsp/spring.mvc.view.suffix=.jsp#log configuration file logging.config=classpath:logback-cms.xml#log path logging.path=/Users/mac/work-tommy/cms-springboot/logs/#data source spring.datasource.name=adminDataSourcespring.datasource.driverClassName = com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://localhost:3306/mycms?useUnicode=true&autoReconnect=true&characterEncoding=utf-8spring.datasource.username = rootspring.datasource.password = 123456
4. Inject configuration using @Configuration
Inject mybatis configuration, please select the paging plugin independently
@Configuration@MapperScan(basePackages = "com.kuwo.dao",sqlSessionTemplateRef = "adminSqlSessionTemplate")public class AdminDataSourceConfig{ @Bean(name = "adminDataSource") @ConfigurationProperties(prefix = "spring.datasource") @Primary public DataSource adminDataSource(){ return DataSourceBuilder.create().build(); } @Bean(name = "adminSqlSessionFactory") @Primary public SqlSessionFactory adminSqlSessionFactory(@Qualifier("adminDataSource")DataSource dataSource)throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //Pagination plugin// PageHelper pageHelper = new PageHelper(); PagePlugin pagePlugin = new PagePlugin();// Properties props = new Properties();// props.setProperty("reasonable", "true");// props.setProperty("supportMethodsArguments", "true");// props.setProperty("returnPageInfo", "check");// props.setProperty("params", "count=countSql");// pageHelper.setProperties(props); // Add plugin bean.setPlugins(new Interceptor[]{pagePlugin}); // Add mybatis configuration file bean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis/mybatis-config.xml")); // Add the mybatis mapping file bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/system/*.xml")); return bean.getObject(); } @Bean(name = "adminTransactionManager") @Primary public DataSourceTransactionManager adminTransactionManager(@Qualifier("adminDataSource")DataSource dataSource){ return new DataSourceTransactionManager(dataSource); } @Bean(name = "adminSqlSessionTemplate") @Primary public SqlSessionTemplate adminSqlSessionTemplate(@Qualifier("adminSqlSessionFactory")SqlSessionFactory sqlSessionFactory)throws Exception { return new SqlSessionTemplate(sqlSessionFactory); }}Add Interceptor configuration, pay attention to the order of addInterceptor, don't mess it up
@Configurationpublic class InterceptorConfigurationextends WebMvcConfigurerAdapter{ @Override public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(new LoginHandlerInterceptor()); }}Add shiro configuration file
Note: I used redis as session cache, but I found a problem with integration with shiro. After the user object is stored, it cannot be type-converted after obtaining it from shiro, so I temporarily gave up redis as session cache.
@Configurationpublic class ShiroConfiguration{ @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.timeout}") private int timeout; @Bean public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor(){ return new LifecycleBeanPostProcessor(); } /** * ShiroFilterFactoryBean handles intercepting resource files. * Note: A single ShiroFilterFactoryBean configuration is or an error is reported, because when * initializing ShiroFilterFactoryBean, it is necessary to inject: SecurityManager * Filter Chain definition description 1. A URL can configure multiple Filters, separated by commas 2. When multiple filters are set, all verification will be passed, and only 3. Some filters can specify parameters, such as perms, roles * */ @Bean public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){ System.out.println("ShiroConfiguration.shirFilter()"); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // SecurityManager shiroFilterFactoryBean.setSuccessUrl("/usersPage"); // If you do not set the default, the "/login.jsp" page in the root directory of the web project will be automatically searched; // If you do not set the default, the "/login.jsp" page in the root directory of the web project will be automatically searched; // The link to be redirected after login is successful shiroFilterFactoryBean.setSuccessUrl("/usersPage"); // Unauthorized interface; shiroFilterFactoryBean.setUnauthorizedUrl("/403"); //Interceptor. Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>(); //Configure the exit filter, the specific exit code Shiro has implemented filterChainDefinitionMap.put("/logout", "logout"); filterChainDefinitionMap.put("/login_toLogin", "anon"); filterChainDefinitionMap.put("/login_login", "anon"); filterChainDefinitionMap.put("/static/login/**","anon"); filterChainDefinitionMap.put("/static/js/**","anon"); filterChainDefinitionMap.put("/uploadFiles/uploadImgs/**","anon"); filterChainDefinitionMap.put("/code.do","anon"); filterChainDefinitionMap.put("/font-awesome/**","anon"); //<!-- Filter chain definition, executed from top to bottom, generally put /** at the bottom -->: This is a pit, if you are not careful, the code will not work; //<!-- authc: All urls must be authenticated before accessing; anon: All urls can be accessed anonymously--> filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } @Bean public SecurityManager securityManager(){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //Set realm. securityManager.setRealm(myShiroRealm()); //Custom cache implementation uses redis //securityManager.setCacheManager(cacheManager()); // Custom session management uses redis securityManager.setSessionManager(sessionManager()); return securityManager; } @Bean public ShiroRealm myShiroRealm(){ ShiroRealm myShiroRealm = new ShiroRealm();// myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return myShiroRealm; }} /** * Enable shiro aop annotation support. * Use proxy method; so code support needs to be enabled; * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){ AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } /** * Configuring shiro redisManager * Use shiro-redis open source plugin* @return */ public RedisManager redisManager(){ RedisManager redisManager = new RedisManager(); redisManager.setHost(host); redisManager.setPort(port); redisManager.setExpire(1800); redisManager.setTimeout(timeout); // redisManager.setPassword(password); return redisManager; } /** * cacheManager cache redis implementation* uses shiro-redis open source plugin* @return */ public RedisCacheManager cacheManager(){ RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager()); return redisCacheManager; } /** * The implementation of RedisSessionDAO shiro sessionDao layer is through redis * uses shiro-redis open source plugin*/ @Bean public RedisSessionDAO redisSessionDAO(){ RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); redisSessionDAO.setRedisManager(redisManager()); return redisSessionDAO; } @Bean public DefaultWebSessionManager sessionManager(){ DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();// sessionManager.setSessionDAO(redisSessionDAO()); return sessionManager; }}Summarize
I spent a day converting the project into springboot and checking various information. I hope this article can help you. I also hope everyone will support Wulin.com more.