01構建第一個SpringBoot工程

第一篇:構建第一個SpringBoot工程

建立項目

  1. 建立工程:Idea-> new Project ->Spring Initializr ->填寫group、artifact ->鉤上web(開啓web功能)->點下一步就好了
  2. maven項目依賴spring-boot-starter-web不只包含spring-boot-starter,還自動開啓了web功能
  3. 使用@RestController註解控制器
  4. 使用@RequestMapping("/")註解路由

啓動springboot

  1. cd到項目主目錄
  2. 清理target: mvn clean
  3. 打包命令: mvn package
  • 編譯報錯:No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
  • 緣由是maven使用jdk編譯,ide使用jre編譯
  • 解決辦法:
<!-- 在pom.xml中添加配置,讓Maven使用jdk編譯 -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
    </configuration>
</plugin>
  • 參考:https://www.cnblogs.com/zienzir/p/9318236.html
  1. 啓動命令:mvn spring-boot:run
  2. jar包方式啓動,cd 到target目錄,java -jar 項目.jar

CommandLineRunner執行定時任務

  1. CommandLineRunner接口主要用於實如今應用初始化後,去執行一段代碼塊邏輯,這段初始化代碼在整個應用生命週期內只會執行一次。
  2. 用法1:和@Component註解一塊兒使用
@Component
public class ApplicationStartupRunner implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());
 
    @Override
    public void run(String... args) throws Exception {
        logger.info("ApplicationStartupRunner run method Started !!");
    }
}
  1. 用法2:和@SpringBootApplication註解一塊兒使用
@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer implements CommandLineRunner {
 
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringBootWebApplication.class);
    }
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
    @Override
    public void run(String... args) throws Exception {
        logger.info("Application Started !!");
    }
}
  1. 使用3:聲明一個實現了CommandLineRunner接口的Bean
public class ApplicationStartupRunner implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());
    @Override
    public void run(String... args) throws Exception {
        logger.info("Application Started !!");
    }
}
  1. 參考:https://www.cnblogs.com/chenpi/p/9696310.html

springboot注入的bean

  1. 代碼以下
// 下面的代碼,在項目啓動時,會執行,
// 打印啓動時加載的bean
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    // 下面使用的是lambda表達式,編譯器根據方法體推測,返回一個CommandLineRunner對象
    return args -> {
        System.out.println("Let's inspect the beans provided by Spring Boot:");
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    };
}

單元測試,能夠直接測試web項目

  1. 經過@RunWith() @SpringBootTest開啓註解
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class FirstProgramApplicationTests {
    @Test
    public void contextLoads() {
    }
    // 獲取服務端口
    @LocalServerPort
    private int port;
    private URL base;
    // 自動注入一個TestRestTemplate對象
    @Autowired
    private TestRestTemplate template;
    // 執行測試以前執行
    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/");
    }
    // 執行測試
    @Test
    public void getHello() throws Exception {
        ResponseEntity<String> response = template.getForEntity(base.toString(),
                String.class);
        assertThat(response.getBody(), equalTo("hello 第一個項目作好了"));
    }
}
  1. 報錯:Could not resolve placeholder 'local.server.port' in value "${local.server.port}
  • 在配置文件中添加:local.server.port=8090
  1. 報錯:No qualifying bean of type 'org.springframework.boot.test.web.client.TestRestTemplate' available
  • 解決:
將頭部的註解修改 
@RunWith(SpringRunner.class) 
@SpringBootTest 
改成: 
@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  • 參考:https://blog.csdn.net/mxj588love/article/details/78604236

參考

  • SpringBoot非官方教程 | 第一篇:構建第一個SpringBoot工程 https://blog.csdn.net/forezp/article/details/70341651
  • Spring boot CommandLineRunner接口使用例子 https://www.cnblogs.com/chenpi/p/9696310.html
相關文章
相關標籤/搜索