1. 程式人生 > >Spring Boot-開發基礎1

Spring Boot-開發基礎1

生產級別的spring應用,搭建程式的腳手架,內建tomcat,推崇約定大於配置

java-jar啟動

存放預設配置的包是啟動器

自己設定引數:.properties 

  • 建立專案,在maven中新增
 <parent>
        <!--父工程-->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

    }
}
@RestController
@RequestMapping
public class HelloController {
//    @RequestMapping(value = "hello", method = RequestMethod.GET)
    @GetMapping("hello")
    public String hello(){
        return "Hello World!!!!!!!!!!!!!!";
    }
}

spring的Java配置(註解)

  • @Configuration:宣告類作為配置類,代替xml檔案
  • @Bean:宣告在方法上,將方法的返回值加入Bean容器裡,代替<bean>
  • @value:屬性注入
  • @PropertySource:指定外部屬性檔案

Druid是Java語言中資料庫連線池。Druid能夠提供強大的監控和擴充套件功能。

@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

SpringBoot的屬性注入

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig2 {
    @Bean
    public DataSource dataSource(JdbcProperties prop){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(prop.getDriverClassName());
        dataSource.setUrl(prop.getUrl());
        dataSource.setUsername(prop.getUsername());
        dataSource.setPassword(prop.getPassword());
        return dataSource;
    }
}
@ConfigurationProperties(prefix = "jdbc")
@PropertySource("classpath:jdbc.properties")// 引用檔案
public class JdbcProperties {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
//省略get/set方法
}