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>
  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://www.cnblogs.com/wang7/p/10775736.html