spring-boot使用教程(一):讓程序跑起來

簡介

spring-boot是由Pivotal團(tuán)隊(duì)提供的全新框架炉爆,其設(shè)計(jì)目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程弯囊。該框架使用了特定的方式來進(jìn)行配置潘明,從而使開發(fā)人員不再需要定義樣板化的配置蛋欣。通過這種方式寡夹,Boot致力于在蓬勃發(fā)展的快速應(yīng)用開發(fā)領(lǐng)域(rapid application development)成為領(lǐng)導(dǎo)者处面。

參考項(xiàng)目:https://github.com/bigbeef/cppba-spring-boot
開源地址:https://github.com/bigbeef
個人博客:http://blog.cppba.com

文件結(jié)構(gòu)

https://github.com/bigbeef/cppba-spring-boot

1.maven的pom.xml配置

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cppbba</groupId>
    <artifactId>cppba-spring-boot</artifactId>
    <packaging>war</packaging>
    <version>1.0.0</version>

    <name>cppba-spring-boot Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.6.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jdk.version>1.7</jdk.version>
        <spring.version>4.3.0.RELEASE</spring.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
    </properties>

    <dependencies>
        <!--spring-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- hibernate-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.20</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>cppba-spring-boot</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.創(chuàng)建Application.java

package com.cppba;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;

import java.net.UnknownHostException;

// same as @Configuration @EnableAutoConfiguration @ComponentScan
@SpringBootApplication
public class Application {
    public static void main(String[] args) throws UnknownHostException {
        SpringApplication app = new SpringApplication(Application.class);
        Environment environment = app.run(args).getEnvironment();
    }
}

3.創(chuàng)建DatabaseConfiguration.java

package com.cppba.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.ApplicationContextException;
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.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
public class DatabaseConfiguration implements EnvironmentAware {

    private Environment environment;
    private RelaxedPropertyResolver datasourcePropertyResolver;

    //從application.yml中讀取資源
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
        this.datasourcePropertyResolver = new RelaxedPropertyResolver(environment,
                "spring.datasource.");
    }

    //datasource
    @Bean(initMethod = "init", destroyMethod = "close")
    public DataSource dataSource() throws SQLException {
        if (StringUtils.isEmpty(datasourcePropertyResolver.getProperty("url"))) {
            System.out.println("Your database connection pool configuration is incorrect!" +
                    " Please check your Spring profile, current profiles are:"+
            Arrays.toString(environment.getActiveProfiles()));
            throw new ApplicationContextException(
                    "Database connection pool is not configured correctly");
        }
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(datasourcePropertyResolver.getProperty("url"));
        druidDataSource.setUsername(datasourcePropertyResolver
                .getProperty("username"));
        druidDataSource.setPassword(datasourcePropertyResolver
                .getProperty("password"));
        druidDataSource.setInitialSize(1);
        druidDataSource.setMinIdle(1);
        druidDataSource.setMaxActive(20);
        druidDataSource.setMaxWait(60000);
        druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
        druidDataSource.setMinEvictableIdleTimeMillis(300000);
        druidDataSource.setValidationQuery("SELECT 'x'");
        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.setTestOnReturn(false);
        return druidDataSource;
    }

    //sessionFactory
    @Bean
    public LocalSessionFactoryBean sessionFactory() throws SQLException{
        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(this.dataSource());
        Properties properties1 = new Properties();
        properties1.setProperty("hibernate.dialect","org.hibernate.dialect.MySQL5Dialect");
        properties1.setProperty("hibernate.show_sql","false");
        localSessionFactoryBean.setHibernateProperties(properties1);
        localSessionFactoryBean.setPackagesToScan("*");
        return localSessionFactoryBean;
    }

    //txManager事務(wù)開啟
    @Bean
    public HibernateTransactionManager txManager() throws SQLException {
        HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
        hibernateTransactionManager.setSessionFactory(sessionFactory().getObject());
        return hibernateTransactionManager;
    }
}

4.創(chuàng)建CommonAction.java(這是一個測試類)

package com.cppba.web;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@Transactional
public class CommonAction {

    @Resource
    private SessionFactory sessionFactory;

    @RequestMapping("test")
    public void test(HttpServletResponse response){
        Session session = sessionFactory.getCurrentSession();
        SQLQuery sqlQuery = session.createSQLQuery("select * from user");
        List list = sqlQuery.list();
        System.out.printf(list.size()+"");
        try {
            response.setContentType("application/json");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("{\"msg\":\"調(diào)用成功\"}");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5.創(chuàng)建application.yml

server:
    port: 8080
    address: localhost

spring:
    datasource:
        url: jdbc:mysql://localhost:3306/cppba
        username: root
        password: root

6.啟動項(xiàng)目

我們點(diǎn)擊啟動按鈕


https://github.com/bigbeef/cppba-spring-boot

控制臺會打印如下內(nèi)容:

https://github.com/bigbeef/cppba-spring-boot
https://github.com/bigbeef/cppba-spring-boot

啟動成功
接下來我們訪問http://127.0.0.1:8080/test
(我的CommonAction中RequestMapping("test"),所以訪問路徑是test)

https://github.com/bigbeef/cppba-spring-boot

到此spring-boot配置成功!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末菩掏,一起剝皮案震驚了整個濱河市魂角,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌智绸,老刑警劉巖野揪,帶你破解...
    沈念sama閱讀 211,884評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異瞧栗,居然都是意外死亡斯稳,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,347評論 3 385
  • 文/潘曉璐 我一進(jìn)店門沼溜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來平挑,“玉大人,你說我怎么就攤上這事系草⊥ㄏǎ” “怎么了?”我有些...
    開封第一講書人閱讀 157,435評論 0 348
  • 文/不壞的土叔 我叫張陵找都,是天一觀的道長唇辨。 經(jīng)常有香客問我,道長能耻,這世上最難降的妖魔是什么赏枚? 我笑而不...
    開封第一講書人閱讀 56,509評論 1 284
  • 正文 為了忘掉前任亡驰,我火速辦了婚禮,結(jié)果婚禮上饿幅,老公的妹妹穿的比我還像新娘凡辱。我一直安慰自己,他們只是感情好栗恩,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,611評論 6 386
  • 文/花漫 我一把揭開白布透乾。 她就那樣靜靜地躺著,像睡著了一般磕秤。 火紅的嫁衣襯著肌膚如雪乳乌。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,837評論 1 290
  • 那天市咆,我揣著相機(jī)與錄音汉操,去河邊找鬼。 笑死蒙兰,一個胖子當(dāng)著我的面吹牛磷瘤,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播癞己,決...
    沈念sama閱讀 38,987評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼膀斋,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了痹雅?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,730評論 0 267
  • 序言:老撾萬榮一對情侶失蹤糊识,失蹤者是張志新(化名)和其女友劉穎绩社,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體赂苗,經(jīng)...
    沈念sama閱讀 44,194評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡愉耙,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,525評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了拌滋。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片朴沿。...
    茶點(diǎn)故事閱讀 38,664評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖败砂,靈堂內(nèi)的尸體忽然破棺而出赌渣,到底是詐尸還是另有隱情,我是刑警寧澤昌犹,帶...
    沈念sama閱讀 34,334評論 4 330
  • 正文 年R本政府宣布坚芜,位于F島的核電站,受9級特大地震影響斜姥,放射性物質(zhì)發(fā)生泄漏鸿竖。R本人自食惡果不足惜沧竟,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,944評論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望缚忧。 院中可真熱鬧悟泵,春花似錦、人聲如沸闪水。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,764評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽敦第。三九已至峰弹,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間芜果,已是汗流浹背鞠呈。 一陣腳步聲響...
    開封第一講書人閱讀 31,997評論 1 266
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留右钾,地道東北人蚁吝。 一個月前我還...
    沈念sama閱讀 46,389評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像舀射,于是被迫代替她去往敵國和親窘茁。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,554評論 2 349

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