之前項(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è)人博客