摘要:當(dāng)禁用時(shí),所有關(guān)聯(lián)對(duì)象都會(huì)即時(shí)加載。不同的驅(qū)動(dòng)在這方便表現(xiàn)不同。參考驅(qū)動(dòng)文檔或充分測(cè)試兩種方法來(lái)決定所使用的驅(qū)動(dòng)。如果設(shè)置為則這個(gè)設(shè)置強(qiáng)制生成的鍵被使用,盡管一些驅(qū)動(dòng)拒絕兼容但仍然有效比如。
SpringMVC相信大家已經(jīng)不再陌生了,大家可能對(duì)于Spring的各種XML配置已經(jīng)產(chǎn)生了厭惡的感覺(jué),Spring官方發(fā)布的Springboot 已經(jīng)很長(zhǎng)時(shí)間了,Springboot是一款“約定優(yōu)于配置”的輕量級(jí)框架;Springboot首先解決的就是各種繁瑣的XML配置,你可以不用任何XML配置,進(jìn)行web服務(wù)的搭建,其次是Springboot本身就繼承了web服務(wù)器,如果說(shuō)前端開(kāi)發(fā)人員想在本地啟動(dòng)后端服務(wù)不需要進(jìn)行各種配置,幾乎可以做到一鍵啟動(dòng)。
再有就是目前大熱的微服務(wù),而Springboot恰恰滿足了快速開(kāi)發(fā)微服務(wù)的開(kāi)發(fā)場(chǎng)景;對(duì)于目前主流的框架Spring+MyBatis+redis的集成,好吧直接看代碼...
以下代碼是整個(gè)開(kāi)發(fā)框架集成完之后的,關(guān)于Spring官方那一套如何編寫(xiě)啟動(dòng)類,如何配置端口這些隨便google一大把的我就不再本文說(shuō)明了。下面的代碼,mybatis mapper我就不貼了,平常怎么寫(xiě)現(xiàn)在也一樣,還有redis存數(shù)據(jù)取數(shù)據(jù)什么的。本文給的都是劃的重點(diǎn)??!
1.數(shù)據(jù)源以及其他的配置文件(PS:說(shuō)好了不配置,怎么剛開(kāi)始就上配置? 答:不配置也可以,如果你想把數(shù)據(jù)源硬編碼寫(xiě)死的話。^_^)
下面給的是YML的配置文件方式,YML被各種主流的開(kāi)發(fā)語(yǔ)言所支持,相當(dāng)于常見(jiàn)的.properties文件。
jedis : pool : host : 127.0.0.1 port : 6379 config : maxTotal: 100 maxIdle: 10 maxWaitMillis : 100000 server : port : 8080 jdbc: datasource: name: test url: jdbc:mysql://127.0.0.1:3306/test username: root password: 123456 # 使用druid數(shù)據(jù)源 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 # MyBatis mybatis: typeAliasesPackage: com.xiaour.spring.boot.entity mapperLocations: classpath*:/com/xiaour/spring/boot/mapper/*.xml configLocation: classpath:mybatis-config.xml # LOGGING logging: level: com.ibatis:DEBUG
2.Springboot啟動(dòng)
package com.tony.spring.boot; import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.support.SpringBootServletInitializer; /** * Created by zhang.tao on 2017/4/19. */ @SpringBootApplication(exclude = MybatisAutoConfiguration.class) @ServletComponentScan @EnableAutoConfiguration @MapperScan("com.tony.spring.boot.mapper") public class Application extends SpringBootServletInitializer implements EmbeddedServletContainerCustomizer { @Value("${server.port}") private int port;//應(yīng)用的端口 /** * 啟動(dòng)入口 * @param args */ public static void main(String ... args){ SpringApplication.run(Application.class, args); } /** * 自定義端口 */ @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setPort(port); } }
3.配置Mysql數(shù)據(jù)源
import java.sql.SQLException; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.alibaba.druid.pool.DruidDataSource; @Configuration @EnableTransactionManagement public class DataBaseConfiguration implements EnvironmentAware { private RelaxedPropertyResolver propertyResolver; private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class); private Environment env; @Override public void setEnvironment(Environment env) { this.env = env; this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.datasource."); } /** * 配置數(shù)據(jù)源 * @Description TODO * @return */ @Bean(name = "dataSource",destroyMethod = "close") public DataSource dataSource() { log.debug(env.getActiveProfiles().toString()); DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(propertyResolver.getProperty("url")); dataSource.setUsername(propertyResolver.getProperty("username"));//用戶名 dataSource.setPassword(propertyResolver.getProperty("password"));//密碼 dataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name")); dataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize"))); dataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive"))); dataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle"))); dataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait"))); dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(propertyResolver.getProperty("timeBetweenEvictionRunsMillis"))); dataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(propertyResolver.getProperty("minEvictableIdleTimeMillis"))); dataSource.setValidationQuery(propertyResolver.getProperty("validationQuery")); dataSource.setTestOnBorrow(Boolean.getBoolean(propertyResolver.getProperty("testOnBorrow"))); dataSource.setTestWhileIdle(Boolean.getBoolean(propertyResolver.getProperty("testWhileIdle"))); dataSource.setTestOnReturn(Boolean.getBoolean(propertyResolver.getProperty("testOnReturn"))); dataSource.setPoolPreparedStatements(Boolean.getBoolean(propertyResolver.getProperty("poolPreparedStatements"))); dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxOpenPreparedStatements"))); try { dataSource.init(); } catch (SQLException e) { } return dataSource; } }
4.Redis數(shù)據(jù)源配置.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * 配置redis數(shù)據(jù)源 * * @ClassName RedisConfig * @author Zhang.Tao * @Date 2017年4月24日 下午5:25:30 * @version V2.0.0 */ @Configuration public class RedisConfig { @Bean(name= "jedis.pool") @Autowired public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config, @Value("${jedis.pool.host}")String host, @Value("${jedis.pool.port}")int port) { return new JedisPool(config, host, port); } @Bean(name= "jedis.pool.config") public JedisPoolConfig jedisPoolConfig (@Value("${jedis.pool.config.maxTotal}")int maxTotal, @Value("${jedis.pool.config.maxIdle}")int maxIdle, @Value("${jedis.pool.config.maxWaitMillis}")int maxWaitMillis) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(maxTotal); config.setMaxIdle(maxIdle); config.setMaxWaitMillis(maxWaitMillis); return config; } }
5.mybatis配置
import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * 初始化SqlSessionFactory * @ClassName MybatisConfiguration * @author Zhang.Tao * @Date 2017年4月24日 下午5:24:56 * @version V2.0.0 */ @Configuration @ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class }) @AutoConfigureAfter({ DataBaseConfiguration.class }) public class MybatisConfiguration implements EnvironmentAware { private static Log logger = LogFactory.getLog(MybatisConfiguration.class); private RelaxedPropertyResolver propertyResolver; @Resource(name = "dataSource") DataSource dataSource; @Override public void setEnvironment(Environment environment) { this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis."); } /** * 初始化SessionFactory * @Description TODO * @return */ @Bean @ConditionalOnMissingBean public SqlSessionFactory sqlSessionFactory() { try { System.err.println(propertyResolver.getProperty("mapperLocations")); SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.setTypeAliasesPackage(propertyResolver .getProperty("typeAliasesPackage")); sessionFactory .setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(propertyResolver .getProperty("mapperLocations"))); sessionFactory .setConfigLocation(new DefaultResourceLoader() .getResource(propertyResolver .getProperty("configLocation"))); return sessionFactory.getObject(); } catch (Exception e) { e.printStackTrace(); logger.warn("Could not confiure mybatis session factory"); return null; } } @Bean @ConditionalOnMissingBean public DataSourceTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource); } }
6.MyBatis配置文件(這個(gè)和Spring沒(méi)關(guān)系,是mybatis的,必須寫(xiě)沒(méi)毛病啊,老鐵)
7.API接口代碼(是不是很6,想不想贊一下?)
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.tony.spring.boot.entity.UserInfo; import com.tony.spring.boot.mapper.UserInfoMapper; import com.tony.spring.boot.utils.JsonUtil; import com.tony.spring.boot.utils.RedisUtil; /** * Created by Administrator on 2017/4/19. */ @RestController @RequestMapping(value="/test") public class TestCtrl { @Autowired private RedisUtil redisUtil; @Autowired private UserInfoMapper userInfoMapper; @RequestMapping(value="/index") public String index(){ return "hello world"; } /** * 向redis存儲(chǔ)值 * @param key * @param value * @return * @throws Exception */ @RequestMapping("/set") public String set(String key, String value) throws Exception{ redisUtil.set(key, value); return "success"; } /** * 獲取redis中的值 * @param key * @return */ @RequestMapping("/get") public String get(String key){ try { return redisUtil.get(key); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 獲取數(shù)據(jù)庫(kù)中的用戶 * @Description TODO * @param id * @return */ @RequestMapping("/getUser/{id}") public String get(@PathVariable("id")int id){ try { System.err.println(id); UserInfo user= userInfoMapper.selectByPrimaryKey(id); return JsonUtil.getJsonString(user); } catch (Exception e) { e.printStackTrace(); } return ""; } }
8.到這里基本上核心的東西差不多了,去Application.java啟動(dòng)就能用了。趕快試試吧
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/67177.html
摘要:中添加攔截器配置如下攔截所有請(qǐng)求,也就是,只攔截開(kāi)頭的請(qǐng)求。在中并沒(méi)有提供配置文件的方式來(lái)配置攔截器,因此需要使用的代碼式配置,配置如下這個(gè)屬性通常并不需要手動(dòng)配置,高版本的會(huì)自動(dòng)檢測(cè)第四點(diǎn)講下靜態(tài)資源映射。 以下內(nèi)容,如有問(wèn)題,煩請(qǐng)指出,謝謝 上一篇講解了springboot的helloworld部分,這一篇開(kāi)始講解如何使用springboot進(jìn)行實(shí)際的應(yīng)用開(kāi)發(fā),基本上尋著sprin...
摘要:概述用久了,深受其約定大于配置的便利性毒害之后,我想回歸到時(shí)代,看看開(kāi)發(fā)模式中用戶是如何參與的。備注當(dāng)然本文所使用的全是非注解的配置方法,即需要在中進(jìn)行配置并且需要遵循各種實(shí)現(xiàn)原則。而更加通用主流的基于注解的配置方法將在后續(xù)文章中詳述。 showImg(https://segmentfault.com/img/remote/1460000015244684); 概述 用久了Sprin...
摘要:萌新一個(gè),感覺(jué)自己才開(kāi)始了程序開(kāi)發(fā)的道路,加油和努力學(xué)習(xí)中。。之前多多少少學(xué)過(guò)也寫(xiě)過(guò)一寫(xiě)后臺(tái)代碼,粗糙到自己無(wú)法忍受。。所以下定決心好好學(xué)習(xí)。。如有錯(cuò)誤或者不好的地方,還請(qǐng)大家指出,共同學(xué)習(xí)。 挖坑中。。萌新一個(gè),感覺(jué)自己才開(kāi)始了程序開(kāi)發(fā)的道路,加油和努力學(xué)習(xí)中。。之前多多少少學(xué)過(guò)也寫(xiě)過(guò)一寫(xiě)后臺(tái)代碼,粗糙到自己無(wú)法忍受。。所以下定決心好好學(xué)習(xí)。。如有錯(cuò)誤或者不好的地方,還請(qǐng)大家指出,共...
摘要:鑒于含有自帶的,還有使用命令啟動(dòng)服務(wù)比較方便,我們就使用包。沒(méi)錯(cuò),他是通過(guò)方法啟動(dòng)的。目錄下主要是資源文件,文件主要是系統(tǒng)配置文件,以后會(huì)經(jīng)常用到。我們需要將提供服務(wù)的應(yīng)用注冊(cè)到服務(wù)中心來(lái)。才能注冊(cè)中服務(wù)中。 我們?cè)趯W(xué)習(xí)springcloud之前,需要先了解springboot框架,springboot框架講究約定優(yōu)于配置,如果之前我們使用過(guò)spring項(xiàng)目的話,用起來(lái)特別的簡(jiǎn)單,可以...
閱讀 1694·2019-08-30 15:54
閱讀 3346·2019-08-26 17:15
閱讀 3536·2019-08-26 13:49
閱讀 2589·2019-08-26 13:38
閱讀 2301·2019-08-26 12:08
閱讀 3065·2019-08-26 10:41
閱讀 1378·2019-08-26 10:24
閱讀 3387·2019-08-23 18:35