zoukankan      html  css  js  c++  java
  • 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) 
    
    

    参考

  • 相关阅读:
    WCF 4.0 进阶系列 – 第十四章 检测服务和路由消息(第三部分)
    WCF 4.0 进阶系列 – 第十五章 构建REST服务(第二部分)
    WCF 4.0 进阶系列 – 第十五章 构建REST服务(第一部分)
    WCF 4.0 进阶系列 – 第十六章 使用回调合约发布和订阅事件(第二部分)
    WCF 4.0 进阶系列 – 第十二章 实现单向操作和异步操作(中)
    asp调用存储过程! PENGHAO
    在b/s开发中经常用到的javaScript技术 PENGHAO
    Windows2003网络服务器安全攻略 PENGHAO
    CSDNBlog非常的不稳定!终于找到个安身之处了! PENGHAO
    ASP 函数语法速查表 PENGHAO
  • 原文地址:https://www.cnblogs.com/wang7/p/10775736.html
Copyright © 2011-2022 走看看