Spring-Boot入門

之前項(xiàng)目中有個(gè)服務(wù)需要獨(dú)立出來鲫忍,同事用springboot改成了微服務(wù)憎账,這兩天沒啥忙的就給拿出瞅瞅?qū)W習(xí)一下~

Demo只是對(duì) 這個(gè)例子 重新寫了一遍加了一些注釋和自己的東西 = =


新建一個(gè)maven項(xiàng)目

我用的是IDEA益兄,新建maven項(xiàng)目時(shí)晨炕,記得添加一個(gè)屬性 archetypeCatalog=internal

archetypeCatalog表示插件使用的archetype元數(shù)據(jù)蒸播,不加這個(gè)參數(shù)時(shí)默認(rèn)為remote匿醒,local场航,即中央倉(cāng)庫(kù)archetype元數(shù)據(jù),由于中央倉(cāng)庫(kù)的archetype太多了廉羔,所以導(dǎo)致很慢溉痢,指定internal來表示僅使用內(nèi)部元數(shù)據(jù)


添加配置

pom.xml文件添加響應(yīng)的配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-tools</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <name>Spring Boot Configuration Processor</name>
    <description>Spring Boot Configuration Processor</description>
    <url>http://projects.spring.io/spring-boot/</url>
    <organization>
        <name>Pivotal Software, Inc.</name>
        <url>http://www.spring.io</url>
    </organization>
    <properties>
        <main.basedir>${basedir}/../..</main.basedir>
    </properties>
    <dependencies>
        <!-- Compile (should stick to the bare minimum) -->
        <dependency>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
        </dependency>
        <!-- Test -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test-support</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <!-- Ensure own annotation processor doesn't kick in -->
                    <proc>none</proc>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

在application.properties中寫入相關(guān)配置

server.port=9000

druid.url=jdbc:mysql://127.0.0.1:3306/test
druid.username=root
druid.password=root
druid.initialSize=1
druid.minIdle=1
druid.maxActive=20
druid.testOnBorrow=true

#springboot默認(rèn)的日志系統(tǒng)是logback
logging.level.tk.mybatis=TRACE

#freemarker 文件的路徑
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.ftl
spring.freemarker.cache=false
spring.freemarker.request-context-attribute=request

#mybatis掃描的文件路徑
mybatis.type-aliases-package=tk.yoruo.springboot.model
mybatis.mapper-locations=classpath:mapper/*.xml

#通用mapper的配置
mapper.mappers=tk.yoruo.springboot.util.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL

#mybatis分頁(yè)插件的配置
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql


靜態(tài)資源的路徑

用了freemarker模版引擎 配置一些靜態(tài)資源文件路徑

package tk.yoruo.springboot.conf;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by LXC on 2017/2/9.
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    /**
     * spring-boot配置外部靜態(tài)資源的方法
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

其他的service層,實(shí)體憋他,controller就不闡述了孩饼。


添加數(shù)據(jù)庫(kù)配置

創(chuàng)建一個(gè)DruidProperties的類

添加一些屬性。并加上@ConfigurationProperties(prefix = "druid")注解竹挡,告訴boot這個(gè)是個(gè)讀取配置文件的類并且從 application.properties 中取前綴為 druid的value镀娶。

接著創(chuàng)建DruidAutoConfiguration類 加上@Configuration告訴boot這個(gè)是配置類。

注入DruidProperties 并加入@Bean

package tk.yoruo.springboot.druid;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;

/**
 * Created by LXC on 2017/2/9.
 */

@Configuration
@EnableConfigurationProperties(DruidProperties.class)
// 對(duì)應(yīng)的類在classpath中有存在時(shí)才會(huì)注入
@ConditionalOnClass(DruidDataSource.class)

// 對(duì)應(yīng)的前綴和屬性名 在classpath中有存在時(shí)才會(huì)注入
@ConditionalOnProperty(prefix = "druid", name = "url")
public class DruidAutoConfiguration {

    @Autowired
    private DruidProperties druidProperties;

    @Bean
    public DruidDataSource dataSource() {

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(druidProperties.getUrl());
        druidDataSource.setUsername(druidProperties.getUsername());
        druidDataSource.setPassword(druidProperties.getPassword());
        if (druidProperties.getInitialSize() > 0) {
            druidDataSource.setInitialSize(druidProperties.getInitialSize());
        }
        if (druidProperties.getMinIdle() > 0) {
            druidDataSource.setMinIdle(druidProperties.getMinIdle());
        }
        if (druidProperties.getMaxActive() > 0) {
            druidDataSource.setMaxActive(druidProperties.getMaxActive());
        }
        druidDataSource.setTestOnBorrow(druidProperties.isTestOnBorrow());
        try {
            druidDataSource.init();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return druidDataSource;
    }
}

接著 在src/main/resources目錄下新建META-INF文件夾揪罕,然后新建spring.factories文件梯码,這個(gè)文件用于告訴Spring Boot去找指定的自動(dòng)配置文件

所以spring.factories內(nèi)容為

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
tk.yoruo.springboot.druid.DruidAutoConfiguration

添加Druid Web監(jiān)控

分別繼承 Druid中的過濾器和servlet。

package tk.yoruo.springboot.druid;

import com.alibaba.druid.support.http.WebStatFilter;

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

/**
 * Created by LXC on 2017/2/8.
 */

@WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*",
        initParams = {
                @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略資源
        })
public class DruidStatFilter extends WebStatFilter {

}


package tk.yoruo.springboot.druid;

import com.alibaba.druid.support.http.StatViewServlet;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

/**
 * Created by LXC on 2017/2/8.
 */

@SuppressWarnings("serial")
@WebServlet(urlPatterns = "/druid/*",
        initParams = {
                @WebInitParam(name = "allow", value = "127.0.0.1"),// IP白名單 (沒有配置或者為空好啰,則允許所有訪問)
//                @WebInitParam(name="deny",value="192.168.16.111"),// IP黑名單 (存在共同時(shí)轩娶,deny優(yōu)先于allow)
                @WebInitParam(name = "loginUsername", value = "admin"),// 用戶名
                @WebInitParam(name = "loginPassword", value = "admin"),// 密碼
                @WebInitParam(name = "resetEnable", value = "true")// 禁用HTML頁(yè)面上的“Reset All”功能
        })
public class DruidStatViewServlet extends StatViewServlet {

}

注意還需要在Application類上加入 @ServletComponentScan的注解,否則掃描不到你添加的servlet坎怪。

package tk.yoruo.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import tk.yoruo.springboot.util.MyMapper;

/**
 * Created by LXC on 2017/2/9.
 */


@Controller
@ServletComponentScan
@EnableWebMvc
//@ComponentScan(basePackages = {"tk.yoruo.springboot.controller","tk.yoruo.springboot.service"})
@SpringBootApplication
@MapperScan(basePackages = "tk.yoruo.springboot.mapper", markerInterface = MyMapper.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @RequestMapping("/")
    String home() {
        return "redirect:countries";
    }

}


注意

Application springboot啟動(dòng)的類罢坝,不建議放在頂級(jí)的包。例如src/main/java下面搅窿。

如果這樣做了會(huì)和我一樣出現(xiàn)這個(gè)錯(cuò)誤

** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.


如果一定要這樣做嘁酿,需要在Application上加這樣的注解。標(biāo)明你要掃描的包

@ComponentScan(basePackages = {"tk.yoruo.springboot.controller","tk.yoruo.springboot.service"})

這樣話靜態(tài)資源會(huì)找不到男应。

那應(yīng)該怎么找到... 我還沒去試 = =

建議別這樣做闹司,放在外面啟動(dòng)服務(wù)時(shí)間會(huì)變久。


歡迎光臨我的個(gè)人博客

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末沐飘,一起剝皮案震驚了整個(gè)濱河市游桩,隨后出現(xiàn)的幾起案子牲迫,更是在濱河造成了極大的恐慌,老刑警劉巖借卧,帶你破解...
    沈念sama閱讀 218,386評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件盹憎,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡铐刘,警方通過查閱死者的電腦和手機(jī)陪每,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來镰吵,“玉大人檩禾,你說我怎么就攤上這事“碳溃” “怎么了盼产?”我有些...
    開封第一講書人閱讀 164,704評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)勺馆。 經(jīng)常有香客問我戏售,道長(zhǎng),這世上最難降的妖魔是什么谓传? 我笑而不...
    開封第一講書人閱讀 58,702評(píng)論 1 294
  • 正文 為了忘掉前任蜈项,我火速辦了婚禮,結(jié)果婚禮上续挟,老公的妹妹穿的比我還像新娘。我一直安慰自己侥衬,他們只是感情好诗祸,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著轴总,像睡著了一般直颅。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上怀樟,一...
    開封第一講書人閱讀 51,573評(píng)論 1 305
  • 那天功偿,我揣著相機(jī)與錄音,去河邊找鬼往堡。 笑死械荷,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的虑灰。 我是一名探鬼主播吨瞎,決...
    沈念sama閱讀 40,314評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼穆咐!你這毒婦竟也來了颤诀?” 一聲冷哼從身側(cè)響起字旭,我...
    開封第一講書人閱讀 39,230評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎崖叫,沒想到半個(gè)月后遗淳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,680評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡心傀,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評(píng)論 3 336
  • 正文 我和宋清朗相戀三年屈暗,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片剧包。...
    茶點(diǎn)故事閱讀 39,991評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡恐锦,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出疆液,到底是詐尸還是另有隱情一铅,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評(píng)論 5 346
  • 正文 年R本政府宣布堕油,位于F島的核電站潘飘,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏掉缺。R本人自食惡果不足惜卜录,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望眶明。 院中可真熱鬧艰毒,春花似錦、人聲如沸搜囱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)蜀肘。三九已至绊汹,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間扮宠,已是汗流浹背西乖。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留坛增,地道東北人获雕。 一個(gè)月前我還...
    沈念sama閱讀 48,158評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像轿偎,于是被迫代替她去往敵國(guó)和親典鸡。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,815評(píng)論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理坏晦,服務(wù)發(fā)現(xiàn)萝玷,斷路器嫁乘,智...
    卡卡羅2017閱讀 134,657評(píng)論 18 139
  • Spring Boot特點(diǎn) 1. 創(chuàng)建獨(dú)立的Spring應(yīng)用程序 2. 嵌入的Tomcat,無(wú)需部署WAR文件(此...
    酒紅色的小貓一閱讀 730評(píng)論 0 0
  • Spring Boot是微服務(wù)架構(gòu)的基礎(chǔ)球碉。相比以前的Spring蜓斧,它主要是省去了大量的樣板式配置,取而代之的是根據(jù)...
    何慶歡閱讀 632評(píng)論 0 1
  • 在送走我爸之后睁冬,我在租房中過起了一個(gè)人的日子挎春,那個(gè)時(shí)候從醫(yī)院養(yǎng)成的早睡早起的習(xí)慣還沒丟,所以日子過得還算規(guī)律豆拨,至少...
    王秀燕閱讀 340評(píng)論 0 0