闲来无事,研究一下spingboot 发现好多地方都不一样了,第一个就是官方默认不支持jsp 于是开始狂找资料 终于让我找到了
首先引入依赖如下:
<!-- tomcat的支持.-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.5.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>8.5.12</version>
</dependency>
<!-- servlet依赖. -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
然后配置application.yml
#配置视图解析器
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
然后在建立webapp文件,
创建启动类
application,java
@SpringBootApplication
public class Application extends SpringBootServletInitializer{
/**
* 主函数
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
} /**
* 支持jsp需要重写此方法
* @param builder
* @return
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(this.getClass());
}
}
右键运行即可
集成 mybatis 首先引入依赖
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-autoconfigure</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.2</version>
</dependency>
<!--通用Mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.8</version>
</dependency>
然后编写mybatis的配置类
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer { @Autowired
DataSource dataSource; @Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("com.lv.gang.entity.business"); //分页插件
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("returnPageInfo", "check");
properties.setProperty("params", "count=countSql");
pageHelper.setProperties(properties); //添加插件
bean.setPlugins(new Interceptor[]{pageHelper}); //添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} /**
* 配置sessionFactory
* @param sqlSessionFactory
* @return
*/
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
} /**
* 配置事物
* @return
*/
@Bean
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
*/
@Configuration
//TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig { @Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.lv.gang.mapper.business");
Properties properties = new Properties();
properties.setProperty("mappers", "tk.mybatis.mapper.common.Mapper");
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
} }
引入分页依赖
<!--分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.3</version>
</dependency>
这时候就可以正常使用mybatis了
接下来集成 redis 引入以下依赖
<!--redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
然后编写redis的配置类
@EnableCaching
@Configuration
public class RedisCacheConfig extends CachingConfigurerSupport { @Autowired
private JedisConnectionFactory jedisConnectionFactory; @Bean
public RedisTemplate redisTemplate() {
StringRedisTemplate redisTemplate = new StringRedisTemplate(jedisConnectionFactory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
} /**
* 配置缓存管理器
* @return
*/
@Bean
public CacheManager cacheManager() {
String[] cacheNames = {"app_default", "users", "blogs", "goods", "configs", "info"};
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate(), Arrays.asList(cacheNames));
redisCacheManager.setDefaultExpiration(86400);
return redisCacheManager;
} /**
* 自定义key.
* 此方法将会根据类名+方法名+所有参数的值生成唯一的一个key,即使@Cacheable中的value属性一样,key也会不一样。
*/
@Bean
@Override
public KeyGenerator keyGenerator() {
return (target, method, objects) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(obj.toString());
}
return sb.toString();
};
}
}
接下来配置application,yml
#配置redis
redis:
host: 127.0.0.1
database: 0
pool:
max-active: 8
min-idle: 2
port: 6379
cluster:
nodes:
这个时候就可以正常使用了
接下来集成 mongo 引入以下依赖
<!--mongo-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
然后配置application.yml
#配置mongo
data:
mongodb:
host: 127.0.0.1
port: 27017
database: gang
接下来我们集成druid数据库连接池 首先引入以下依赖
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>1.5.8.RELEASE</version>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.3</version>
</dependency>
然后配置application.yml
#配置数据源
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useAffectedRows=true&allowMultiQueries=true
username: root
password:
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
接下来集成shiro 首先引入以下依赖
<!-- shiro spring. -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- shiro ehcache -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.2</version>
</dependency>
编写shiro的配置类
@Configuration
public class ShiroConfiguration {
@Autowired
private CacheManager cacheManager;
/**
* 配置shiro过滤器
* @param manager
* @return
*/
@Bean(name="shiroFilter")
public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager) {
ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
bean.setSecurityManager(manager);
//配置登录的url和登录成功的url
bean.setLoginUrl("/login");
bean.setSuccessUrl("/home");
//配置访问权限, 必须为LinkedHashMap
LinkedHashMap<String, String> filterChainDefinitionMap=new LinkedHashMap<>();
filterChainDefinitionMap.put("/index*", "anon"); //表示可以匿名访问
filterChainDefinitionMap.put("/logout*","anon");
filterChainDefinitionMap.put("/jsp/error.jsp*","anon");
filterChainDefinitionMap.put("/static/**","anon");
filterChainDefinitionMap.put("/*", "authc");//表示需要认证才可以访问
bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return bean;
}
//配置核心安全事务管理器
@Bean(name="securityManager")
public SecurityManager securityManager(@Qualifier("authRealm") ShiroRealm authRealm) {
System.err.println("--------------shiro已经加载----------------");
DefaultWebSecurityManager manager=new DefaultWebSecurityManager();
//设置自定义realm
manager.setRealm(authRealm);
//设置缓存管理
manager.setCacheManager(cacheManager);
return manager;
} /**
* 配置缓存管理器
* @return
*/
@Bean
public CacheManager cacheManager(){
EhCacheManager cacheManager=new EhCacheManager();
cacheManager.setCacheManagerConfigFile("classpath:shiro-cache.xml");
return cacheManager;
} /**
* 自定义Realm 继承自AuthorizingRealm
* @param matcher
* @return
*/
@Bean(name="authRealm")
public ShiroRealm authRealm(@Qualifier("credentialsMatcher") CredentialsMatcher matcher) {
ShiroRealm authRealm=new ShiroRealm();
authRealm.setCredentialsMatcher(matcher);
return authRealm;
}
//配置自定义的密码比较器
@Bean(name="credentialsMatcher")
public CredentialsMatcher credentialsMatcher() {
HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
credentialsMatcher.setStoredCredentialsHexEncoded(true);
credentialsMatcher.setHashAlgorithmName("MD5");
credentialsMatcher.setHashIterations(1);
return credentialsMatcher;
}
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
return new LifecycleBeanPostProcessor();
}
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator creator=new DefaultAdvisorAutoProxyCreator();
creator.setProxyTargetClass(true);
return creator;
} /**
* 配置 securityManager
* @param manager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager manager) {
AuthorizationAttributeSourceAdvisor advisor=new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(manager);
return advisor;
}
}
编写 自定义的realm
public class ShiroRealm extends AuthorizingRealm {
/**
* 认证方法
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
} /**
* 授权方法
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
} /**
* 缓存清楚方法
*/
public void clearCached() {
PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
super.clearCache(principals);
}
}
此时已经集成完毕 下篇讲解springboot 集成dubbo和mq 请持续关注
这是deamo的下载地址