<projectxmlns="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>
<groupId>com.nes.spring.boot</groupId>
<artifactId>SpringBootDemo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Compile -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<!-- spring boot mavenplugin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
<dependencyManagement> <dependencies> <dependency> <!-- Import dependency management from Spring Boot --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>1.2.3.RELEASE</version> <type>pom</type> <scope>import</scope><!—这个地方--> </dependency> </dependencies> </dependencyManagement>
<properties> <java.version>1.8</java.version> </properties>
<!-- 支持热部署 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.2.5.RELEASE</version> </dependency>
@RestController
@EnableAutoConfiguration
public class Application {
@RequestMapping("/") String home() {
return"Hello World!";
}
@RequestMapping("/now") String hehe() {
return"现在时间:" + (new Date()).toLocaleString();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
com
+- example
+- myproject
+- Application.java
+- domain
| +- Customer.java
| +- CustomerRepository.java
+- service
| +- CustomerService.java
+- web
+- CustomerController.java
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
publicclassMyConfiguration {
}
SpringApplication.run(Application.class, args);
SpringApplication application = new SpringApplication(Application.class); application.run(args);
new SpringApplicationBuilder() .showBanner(false) .sources(Application.class) .run(args);
# LOGGING logging.path=/var/logs logging.file=myapp.log logging.config= # location of config file (default classpath:logback.xml for logback) logging.level.*= # levels for loggers, e.g. "logging.level.org.springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF) # EMBEDDED SERVER CONFIGURATION (ServerProperties) server.port=8080 server.address= # bind to a specific NIC server.session-timeout= # session timeout in seconds server.context-parameters.*= # Servlet context init parameters, e.g. server.context-parameters.a=alpha server.context-path= # the context path, defaults to '/' server.servlet-path= # the servlet path, defaults to '/'
my.secret=random.valuemy.number={random.int}
my.bignumber=random.longmy.number.less.than.ten={random.int(10)}
my.number.in.range=${random.int[1024,65536]}
name=Isea533 server.port=8080
name: Isea533 server: port: 8080
SpringApplication application = new SpringApplication(Application.class);
Map<String, Object>defaultMap = new HashMap<String, Object>();
defaultMap.put("name", "Isea-Blog");
//还可以是Properties对象
application.setDefaultProperties(defaultMap);
application.run(args);
2.2 应用(使用)属性
2.2.1 @Value(“${xxx}”)
这种方式是最简单的,通过@Value注解可以将属性值注入进来。
2.2.2 @ConfigurationProperties
Spring Boot 可以方便的将属性注入到一个配置对象中。例如:
my.name=Isea533
my.port=8080
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
对应对象:
@ConfigurationProperties(prefix="my")
publicclassConfig {
private String name;
private Integer port;
private List<String> servers = newArrayList<String>();
public String geName(){
returnthis.name;
}
public Integer gePort(){
returnthis.port;
}
public List<String>getServers() {
returnthis.servers;
}
}
name=isea533 jdbc.username=root jdbc.password=root ...
@ConfigurationProperties
publicclassConfig {
private String name;
privateJdbcjdbc;
class Jdbc {
private String username;
private String password;
//getter...
}
public Integer gePort(){
returnthis.port;
}
publicJdbcgetJdbc() {
returnthis.jdbc;
}
}
@ConfigurationProperties(prefix = "foo")
@Bean
publicFooComponentfooComponent() {
...
}
app.name=MyApp
app.description=${app.name} is a Spring Boot application
server.port=${port:8080}
@Component
@ConfigurationProperties(prefix="person")
publicclassConnectionSettings {
private String firstName;
}
@Component
@ConfigurationProperties(prefix="connection")
publicclassConnectionSettings {
@NotNull
privateInetAddressremoteAddress;
// ... getters and setters
}
spring: datasource: name: test url: jdbc:mysql://192.168.16.137:3306/test username: root password: # 使用druid数据源 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
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency>
mybatis: mapperLocations: classpath:mapper/*.xml typeAliasesPackage: tk.mapper.model
/**
* MyBatis基础配置
*
* @authorliuzh
* @since 2015-12-19 10:11
*/
@Configuration
@EnableTransactionManagement
publicclassMyBatisConfigimplementsTransactionManagementConfigurer {
@Autowired
DataSourcedataSource;
@Bean(name = "sqlSessionFactory")
publicSqlSessionFactorysqlSessionFactoryBean() {
SqlSessionFactoryBean bean = newSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("tk.mybatis.springboot.model");
//分页插件
PageHelperpageHelper = newPageHelper();
Properties properties = new Properties();
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("returnPageInfo", "check");
properties.setProperty("params", "count=countSql");
pageHelper.setProperties(properties);
//添加插件
bean.setPlugins(new Interceptor[]{pageHelper});
//添加XML目录
ResourcePatternResolver resolver = newPathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
returnbean.getObject();
} catch (Exception e) {
e.printStackTrace();
thrownewRuntimeException(e);
}
}
@Bean
publicSqlSessionTemplatesqlSessionTemplate(SqlSessionFactorysqlSessionFactory) {
returnnewSqlSessionTemplate(sqlSessionFactory);
}
@Bean
@Override
publicPlatformTransactionManagerannotationDrivenTransactionManager() {
returnnewDataSourceTransactionManager(dataSource);
}
}
/**
* MyBatis扫描接口
*
* @authorliuzh
* @since 2015-12-19 14:46
*/
@Configuration
//注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
publicclassMyBatisMapperScannerConfig {
@Bean
publicMapperScannerConfigurermapperScannerConfigurer() {
MapperScannerConfigurermapperScannerConfigurer = newMapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("tk.mybatis.springboot.mapper");
//配置通用mappers
Propertiesproperties=newProperties();
properties.setProperty("mappers", "tk.mybatis.springboot.util.MyMapper");
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
//这里使用的通用Mapper的MapperScannerConfigurer,所有有下面这个方法
mapperScannerConfigurer.setProperties(properties);
returnmapperScannerConfigurer;
}
}
/META-INF/resources/
/resources/
/static/
/public/
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
@Override
publicvoidaddResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/mystatic/**")
.addResourceLocations("classpath:/mystatic/");
}
spring.mvc.static-path-pattern=/** # Path pattern used forstatic resources.
└─resources │ application.yml │ ├─static │ ├─css │ │index.css │ │ │ └─js │ index.js │ └─templates index.ftl
<linkrel="stylesheet"type="text/css"href="/css/index.css" rel="external nofollow" > <scripttype="text/javascript"src="/js/index.js"></script>
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>1.11.3</version> </dependency>
<scripttype="text/javascript" src="/webjars/jquery/1.11.3/jquery.js"></script>
<dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator</artifactId> </dependency>
@Controller
publicclassWebJarController {
privatefinalWebJarAssetLocatorassetLocator = newWebJarAssetLocator();
@ResponseBody
@RequestMapping("/webjarslocator/{webjar}/**")
publicResponseEntitylocateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
try {
String mvcPrefix = "/webjarslocator/" + webjar + "/";
String mvcPath =
(String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String fullPath =
assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length()));
returnnewResponseEntity(newClassPathResource(fullPath), HttpStatus.OK);
} catch (Exception e) {
returnnewResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
<script type="text/javascript"src="/webjarslocator/jquery/jquery.js"></script>
<script type="text/javascript"src="/js/sample.js?v=1.0.1"></script>
spring.resources.chain.strategy.content.enabled=true spring.resources.chain.strategy.content.paths=/**
@ControllerAdvice
publicclassControllerConfig {
@Autowired
ResourceUrlProviderresourceUrlProvider;
@ModelAttribute("urls")
publicResourceUrlProviderurls() {
returnthis.resourceUrlProvider;
}
}
spring.resources.chain.strategy.fixed.enabled=true spring.resources.chain.strategy.fixed.paths=/js/**,/v1.0.0/** spring.resources.chain.strategy.fixed.version=v1.0.0
<script type="text/javascript"src="${urls.getForLookupPath('/js/index.js')}"></script>
<script type="text/javascript"src="/v1.0.0/js/index.js"></script>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有