springboot項目搭建及經常使用技術整合

.在你創建的工程下建立 Module 選擇Spring initializr建立。 html

 

 二.在Type處選擇: Maven Project(項目的構建工具)java

 

.建立依賴時勾上web,mybatis,mysql(這個看你我的須要吧,能夠自主選擇)mysql

 

 

 

創建好的項目結構以下:git

 

DemoApplication代碼:github

@ComponentScan(basePackages = {"com.example.demo.web", "com.example.demo.config"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@PropertySource(value = { "classpath:config/jdbc.properties"}, ignoreResourceNotFound = false)//未找到文件時報錯
public class DemoApplication {

   public static void main(String[] args) {
      //方式一
//    SpringApplication.run(DemoApplication.class, args);
      //方式二
      SpringApplication SpringApplication = new SpringApplication(DemoApplication.class);
      SpringApplication.setBannerMode(Banner.Mode.OFF);//關閉banner圖
      SpringApplication.run(args);
   }
}

 

注意要加exclude = DataSourceAutoConfiguration.class,不然沒有配置數據源時會報錯:web

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.redis

Reason: Failed to determine a suitable driver classspring

 


啓動方式:sql

1、啓動類中右鍵執行main方法;數據庫

2Terminal命令行中直接執行命令:mvn spring-boot:run   (點擊Xclose session即關閉項目)

3edit Configurations中添加maven命令,注意Command line中只有spring-boot:run,沒有mvn

4、執行mvn install生成jar包,執行命令如:java -jar demo-0.0.1-SNAPSHOT.jar 啓動

 


 啓動banner圖設置:

打開地址生成banner文案:http://patorjk.com/software/taag/#p=display&h=3&v=3&f=4Max&t=springboot

複製生成的文本保存到banner.txt放到maven項目resouces目錄下,啓動便可看到效果。若要更改命名或者存放位置可經過配置更改:

banner.location= classpath:banner.txt

若要關閉可經過:

代碼方式:SpringApplication.setBannerMode(Banner.Mode.OFF);

配置方式:spring.main.banner-mode= off(默認console)

 


 自定義消息轉化器

 方式一:

在@Configuration的類中添加消息轉化器的@bean加入到Spring容器,就會被Spring Boot自動加入到容器中。

@Bean
@ConditionalOnMissingBean//bean不存在狀況下建立
public StringHttpMessageConverter stringHttpMessageConverter(){
   StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));
   return converter;
}

效果至關於在xml文件中配置bean標籤,此配置在spring容器中的名字即方法名,故通常方法名便是bean名

 

方式二:

自定義springmvc配置

有些時候咱們須要自已配置SpringMVC而不是採用默認,好比說增長一個攔截器,這個時候就得經過實現WebMvcConfigurer而後重寫父類中的configureMessageConverters方法進行擴展。

@Configuration
public class NewMvcConfig implements WebMvcConfigurer{

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                    throws Exception {
                System.out.println("新 de 自定義攔截器............");
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                                   ModelAndView modelAndView) throws Exception {

            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                        Exception ex) throws Exception {
            }
        };
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }

    // 自定義消息轉化器的第二種方法
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter converter  = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converters.add(converter);
    }

}

@PropertySource({"classpath:static/testpro.properties"})引入properties文件

可經過註解:@Value("${test.my.name}")在bean屬性中直接獲取properties屬性值

@ImportResource({"classpath:config.xml","classpathsome.xml"})引入xml文件

 


整合mybatis

Mybatis和Spring Boot的整合有兩種方式:

第一種:使用mybatis官方提供的Spring Boot整合包實現,地址:https://github.com/mybatis/spring-boot-starter

第二種:使用mybatis-spring整合的方式,也就是咱們傳統的方式

這裏咱們推薦使用第二種,由於這樣咱們能夠很方便的控制Mybatis的各類配置。

 

1springbootapplication類中配置數據源類

@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.driverClassName}")
private String jdbcDriverClassName;
@Value("${jdbc.username}")
private String jdbcUsername;
@Value("${jdbc.password}")
private String jdbcPassword;

@Bean(destroyMethod = "close")
public DataSource dataSource() {
   DruidDataSource dataSource = new DruidDataSource();

   dataSource.setDriverClassName(jdbcDriverClassName);
   dataSource.setUrl(jdbcUrl);
   dataSource.setUsername(jdbcUsername);
   dataSource.setPassword(jdbcPassword);
   return dataSource;
}

 

2、建立mybatis配置類

@Configuration
public class MyBatisConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    @ConditionalOnMissingBean //當容器裏沒有指定的Bean的狀況下建立該對象
    public SqlSessionFactoryBean sqlSessionFactory() {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 設置數據源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 設置mybatis的主配置文件
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource mybatisConfigXml = resolver.getResource("classpath:config/mybatis-config.xml");
        sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
        // 設置別名包
        sqlSessionFactoryBean.setTypeAliasesPackage("com.example.demo.model");
        //mapper文件路徑匹配
        Resource[] mapperResourceList = null;
        try {
            mapperResourceList = new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactoryBean.setMapperLocations(mapperResourceList);

        return sqlSessionFactoryBean;
    }
}

 

3、建立mapper接口掃描類

@Configuration
@AutoConfigureAfter(MyBatisConfig.class) //保證在MyBatisConfig實例化以後再實例化該類
public class MapperScannerConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.example.demo.dao");
        return mapperScannerConfigurer;
    }
}

 

4、設置事務管理

當引入jdbc依賴以後,Spring Boot會自動默認分別注入DataSourceTransactionManager或JpaTransactionManager,因此咱們不須要任何額外配置就能夠用@Transactional註解進行事務的使用。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

 注意引入配置文件:

@PropertySource(value = { "classpath:config/jdbc.properties"}, ignoreResourceNotFound = false)//最好設置未找到文件時報錯

 

mybatis-config.xml文件內容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!-- 全局參數 -->
    <settings>
        <!-- 使全局的映射器啓用或禁用緩存。 -->
        <setting name="cacheEnabled" value="true"/>
        <!-- 全局啓用或禁用延遲加載。當禁用時,全部關聯對象都會即時加載。 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 設置關聯對象加載的形態,此處爲按需加載字段(加載字段由SQL指 定),不會加載關聯表的全部字段,以提升性能 -->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!-- 是否容許單條sql 返回多個數據集  (取決於驅動的兼容性) default:true -->
        <setting name="multipleResultSetsEnabled" value="true"/>
        <!-- 是否可使用列的別名 (取決於驅動的兼容性) default:true -->
        <setting name="useColumnLabel" value="true"/>
        <!-- 容許JDBC 生成主鍵。須要驅動器支持。若是設爲了true,這個設置將強制使用被生成的主鍵,有一些驅動器不兼容不過仍然能夠執行。  default:false  -->
        <setting name="useGeneratedKeys" value="false"/>
        <!-- 指定 MyBatis 如何自動映射 數據基表的列 NONE:不隱射 PARTIAL:部分  FULL:所有  -->  
        <setting name="autoMappingBehavior" value="PARTIAL"/>
        <!-- 這是默認的執行類型  (SIMPLE: 簡單; REUSE: 執行器可能重複使用prepared statements語句;BATCH: 執行器能夠重複執行語句和批量更新)  -->
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <!-- 使用駝峯命名法轉換字段,自動映射數據庫下劃線 到駝峯字段。 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 容許使用rowbounds嵌套語句 -->
        <setting name="safeRowBoundsEnabled" value="false"/>
        <!-- 設置本地緩存範圍 session:就會有數據的共享  statement:語句範圍 (這樣就不會有數據的共享 ) defalut:session -->
        <setting name="localCacheScope" value="SESSION"/>
        <!-- 設置但JDBC類型爲空時,某些驅動程序 要指定值,default:OTHER,插入空值時不須要指定類型 -->
        <!-- <setting name="jdbcTypeForNull" value="NULL"/> -->
        <!-- 指定對象的方法啓用懶加載 -->
        <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
    </settings>

      <plugins>
          <!-- 分頁插件 -->
          <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 數據庫類型,可選值爲oracle,mysql,mariadb,sqlite,hsqldb,postgresql -->
            <!-- <property name="dialect" value="mysql"/> -->
        </plugin>
      </plugins>
      
      <!-- <typeAliases>
        <package name="com.xiaomu.context.config.model"/>
    </typeAliases> -->

</configuration>

 


整合redis

1、引入springbootredis

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
   <!-- 1.5的版本默認採用的鏈接池技術是jedis  2.0以上版本默認鏈接池是lettuce, 在這裏採用jedis,因此須要排除lettuce的jar -->
   <exclusions>
      <exclusion>
         <groupId>redis.clients</groupId>
         <artifactId>jedis</artifactId>
      </exclusion>
      <exclusion>
         <groupId>io.lettuce</groupId>
         <artifactId>lettuce-core</artifactId>
      </exclusion>
   </exclusions>
</dependency>
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.29</version>
</dependency>
<!-- 添加jedis客戶端 -->
<dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
</dependency>
<!--spring2.0集成redis所需common-pool2-->
<!-- 必須加上,jedis依賴此  -->
<!-- spring boot 2.0 的操做手冊有標註 你們能夠去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/-->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-pool2</artifactId>
   <version>2.4.2</version>
</dependency>

 

2application.properties配置文件中配置redis

# 鏈接工廠使用的數據庫索引(默認爲0)
spring.redis.database= 0
# Redis服務器主機。
spring.redis.host= 127.0.0.1
# redis服務器端口
spring.redis.port= 6380
# 登陸redis服務器的密碼。
spring.redis.password=
# 給定時間池能夠分配的最大鏈接數。 使用負值爲無限制。
spring.redis.pool.max-active= 100
# 池中「空閒」鏈接的最大數量。 使用負值來表示無限數量的空閒鏈接。
spring.redis.pool.max-idle= 10
# 鏈接分配在池耗盡以前在拋出異常以前應阻止的最大時間量(以毫秒爲單位)。 使用負值無限期地阻止。
spring.redis.pool.max-wait= -1
# 定義池中維護的最小空閒鏈接數。 此設置只有在正值時纔有效果。
spring.redis.pool.min-idle= 0
# 鏈接超時(毫秒)。
spring.redis.timeout= 1000

 

3、配置redisconfig,配置的redisTemplate用於存取對象,普通字符串存取直接使用StringRedisTemplate便可

@Configuration
public class RedisConfig{

    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory 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
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer); // key序列化
        redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value序列化
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

 

4、寫redis工具方法

@Component
public class RedisClient {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 刪除緩存
     * @param key 能夠傳一個值 或多個
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * 普通緩存獲取
     * @param key 鍵
     * @return*/
    public String get(String key) {
        return key == null ? null : stringRedisTemplate.opsForValue().get(key);
    }

    public Object getObj(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通緩存放入
     * @param key 鍵
     * @param value 值
     * @return true成功 false失敗
     */
    public boolean set(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
View Code

 


配置freemarker

1、引入freemarker依賴

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

 

2、配置freemarker

spring.freemarker.template-loader-path=classpath:/page/
spring.freemarker.charset=utf-8
spring.freemarker.cache=false
spring.freemarker.suffix=.ftl

 

3、寫controller和頁面(model類或者map放值均可以加入到頁面)

@RequestMapping(value="testpage",method= RequestMethod.GET)
public String testPage(Map<String,Object> map, Model model){
    model.addAttribute("test1","test值放入");
    map.put("test","test值放入2");
    return "page";
}

 


配置攔截器

1、寫攔截器實現

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("攔截器先行方法。。。123 ");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        System.out.println("攔截器後置方法。。。abc");
    }
}

 

2、繼承WebMvcConfigurationSupport添加攔截器並設置攔截路徑

@Configuration
public class SpringMVCConfig extends WebMvcConfigurationSupport {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加攔截器並設置攔截路徑
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/test*/**");
    }
}

 


打包部署

1、更改包屬性爲war工程:<packaging>war</packaging>

2、添加tomcat依賴並設置爲provider

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-tomcat</artifactId>
   <scope>provided</scope>
</dependency>

 

3springboot入口類繼承SpringBootServletInitializer並重寫configure方法

@ComponentScan(basePackages = {"com.example.demo"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@PropertySource(value = { "classpath:config/jdbc.properties"}, ignoreResourceNotFound = false)
public class DemoApplication extends SpringBootServletInitializer{
   //。。。
   //重寫方法用於部署到tomcat中運行
   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
//    return super.configure(builder);
      return builder.sources(DemoApplication.class);
   }
}

 

4、執行maven命令package打包成war包部署便可。

說明:打包後的war包解壓後WEB-INFO目錄下沒有web.xml文件,web入口由繼承的SpringBootServletInitializer類在org目錄下生成了不少關於項目入口的類

 


springboot整合緩存cache

第一步: 導入spring-boot-starter-cache模塊

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

 注:配置文件中spring.cache.type=redis指定緩存類型

 

第二步: @EnableCaching開啓緩存

@ComponentScan(basePackages = {"com.example.demo"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@PropertySource(value = { "classpath:config/jdbc.properties"}, ignoreResourceNotFound = false)
@EnableCaching
public class DemoApplication extends SpringBootServletInitializer{
    ...
}

 

第三步: 使用緩存註解

//@CachePut: 既調用方法,又更新緩存數據;同步更新緩存
//修改了數據庫的某個數據,同時更新緩存
//運行:
// 1.先調用目標方法
// 2.將目標方法的結果緩存起來
@Override
@CachePut(value=CACHE_NAME,key = "#sysmenu.autoId")
public SysMenu updateMenu(SysMenu sysmenu) {
   sysMenuDao.update(sysmenu);
   return sysmenu;
}

//@CacheEvict:緩存清除
//key:指定要清除的數據
//allEntries = true : 指定清除這個緩存中的全部數據
//beforeInvocation=fales: 默認表明緩存清除操做是在方法執行以後執行;若是出現異常緩存就不會清除
//beforeInvocation=true  表明清除緩存操做是在方法運行以前執行,不管方法是否出現異常,緩存都清除
@Override
@CacheEvict(value=CACHE_NAME,key = "#menu_id", beforeInvocation = true)
public void delete(String menu_id) {
   sysMenuDao.delete(menu_id);
}

@Override
public int add(SysMenu sysMenu) {
   return sysMenuDao.add(sysMenu);
}

//查詢時根據指定的參數查詢緩存有無數據,有則直接返回,無則調用方法後將返回值放入緩存
//注意unless條件爲真不緩存,記得指定結果爲空不緩存,不然查詢會緩存空結果致使如有此值新增將查詢不到正確數據
@Override
@Cacheable(value=CACHE_NAME,key = "#autoId", unless = "#result==null")
public SysMenu getByAutoId(String autoId){
   return sysMenuDao.getByAutoId(autoId);
}

 

註解及參數說明:

@Cacheable

@Cacheable 的做用 主要針對方法配置,可以根據方法的請求參數對其結果進行緩存

參數

解釋

example

value

緩存的名稱,在 spring 配置文件中定義,必須指定至少一個

例如:

@Cacheable(value=」mycache」)

@Cacheable(value={」cache1」,」cache2」}

key

緩存的 key,能夠爲空,若是指定要按照 SpEL 表達式編寫,若是不指定,則缺省按照方法的全部參數進行組合

@Cacheable(value=」testcache」,key=」#userName」)

condition

緩存的條件,能夠爲空,使用 SpEL 編寫,返回 true 或者 false,只有爲 true 才進行緩存

@Cacheable(value=」testcache」,condition=」#userName.length()>2」)

@CachePut

@CachePut 的做用 主要針對方法配置,可以根據方法的請求參數對其結果進行緩存,和 @Cacheable 不一樣的是,它每次都會觸發真實方法的調用

參數

解釋

example

value

緩存的名稱,在 spring 配置文件中定義,必須指定至少一個

@CachePut(value=」my cache」)

key

緩存的 key,能夠爲空,若是指定要按照 SpEL 表達式編寫,若是不指定,則缺省按照方法的全部參數進行組合

@CachePut(value=」testcache」,key=」#userName」)

condition

緩存的條件,能夠爲空,使用 SpEL 編寫,返回 true 或者 false,只有爲 true 才進行緩存

@CachePut(value=」testcache」,condition=」#userName.length()>2」)

@CacheEvict

@CachEvict 的做用 主要針對方法配置,可以根據必定的條件對緩存進行清空

參數

解釋

example

value

緩存的名稱,在 spring 配置文件中定義,必須指定至少一個

@CacheEvict(value=」my cache」)

key

緩存的 key,能夠爲空,若是指定要按照 SpEL 表達式編寫,若是不指定,則缺省按照方法的全部參數進行組合

@CacheEvict(value=」testcache」,key=」#userName」)

condition

緩存的條件,能夠爲空,使用 SpEL 編寫,返回 true 或者 false,只有爲 true 才進行緩存

@CacheEvict(value=」testcache」,condition=」#userName.length()>2」)

allEntries

是否清空全部緩存內容,缺省爲 false,若是指定爲 true,則方法調用後將當即清空全部緩存

@CachEvict(value=」testcache」,allEntries=true)

beforeInvocation

是否在方法執行前就清空,缺省爲 false,若是指定爲 true,則在方法尚未執行的時候就清空緩存,缺省狀況下,若是方法執行拋出異常,則不會清空緩存

@CachEvict(value=」testcache」beforeInvocation=true)

@CacheConfig

@Cacheable(value="xxx")註解在類上,統一聲明方法中的value屬性,若是你在你的方法寫別的名字,那麼依然以方法的名字爲準。

參考:https://blog.csdn.net/u012240455/article/details/80844361

相關文章
相關標籤/搜索