springboot使用(一)

例子均来自官网

官网有很多和其它 模块接的例子,如果用springboot迷茫的时候,这真是一剂良药

spring_boot 最简单的例子

  • pom.xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>1.4.3.RELEASE</version>
    </dependency>


</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.0.2</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>

</build>
  • Example.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
public class Example {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}
  • 说明
    直接运行Example.java的main函数,
    不需要配置文件,springboot会默认,
    文中使用了spring-web,spring-mvc, springboot是只要classpath有,它就默认使用了.
    启动后直接访问 http://127.0.0.1:8080/
    注意 spring-boot-starter-web ,springboot 使用其它的模块,都用这种方式,会有各种各样的starter

  • 一些命令行

$ mvn spring-boot:run
  • 打成可运行jar包
    mvn package
    使用:
java -jar target/myproject-0.0.1-SNAPSHOT.jar

自定义 配置

不可能总是用默认,如果要自己配置呢?
程序启动的时候,我们会看到banner

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.3.RELEASE)

如果你不爽这个东西,是可以配置下不出现,可能通过以下来设置

spring:
  main:
    banner-mode: "on"

既然是个web,想定义一下端口和项目名

server:
  port: 8081
  context-path: /myproject

那这些配置在哪?官网是用YAML 来配置,
在resources 里加 application.yml

server:
  port: 8081
  context-path: /myproject
spring:
  main:
    banner-mode: "on"

这样就可以达到配置的效果了.

也可以通过这种方式配置,少用,但要知道这种链式风格

public static void main(String[] args) throws Exception {
    new SpringApplicationBuilder()
            .sources(Parent.class)
            .child(Example.class)
            .bannerMode(Banner.Mode.OFF)
            .run(args);
}

使用配置文件的值

  • @Value使用
    配置文件application.yml:
env: debug

代码使用:

    @Value("${env}")
    private String env;
  • 如果配置有点复杂可以直接用实体来定:
connection:
  username: admin
  password: admin_pwd

FooProperties 这个类

@Component
@ConfigurationProperties(prefix="connection")
public class FooProperties {

    private String username;
    private String password ;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

使用:

@Autowired
FooProperties fooProperties;

关于日志,切换log组件

  • springboot默认是logback
    加上logback.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
            </pattern>
        </layout>
    </appender>

    <!-- 日志输出级别 -->
    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>
  • 如果喜欢用log4j2
    1,把pom.xml 改下
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

2,新增mylog4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout>
                <pattern>%d %p %C{1.} [%t] %m%n</pattern>
            </PatternLayout>
        </Console>
    </Appenders>

    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>

3,名字叫mylog4j2.xml,肯定不标准,这里手动指定一下
在application.yml中写上

logging:
  config: classpath:mylog4j2.xml

相关的代码

https://github.com/huawumingguo/springbootsample/tree/master/springbootbasic

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot是一个由Pivotal团队开发的框架,它将常用的SpringSpringMVC、data-jpa等框架封装在一起,帮助开发者隐藏框架整合的细节,实现敏捷开发。\[2\]在SpringBoot中,可以使用启动器(starter)来简化配置。启动器是一组依赖的集合,它会默认进行一些配置设置,例如使用spring-boot-starter-web启动器可以快速搭建一个Web应用。\[1\] 在SpringBoot中,可以使用@SpringBootApplication注解来标记启动类。@SpringBootApplication是一个组合注解,包含了@Configuration、@EnableAutoConfiguration和@ComponentScan等注解。@Configuration表示启动类是一个配置类,@EnableAutoConfiguration实现自动装配,@ComponentScan用于扫描注解。\[3\] SpringBoot的配置文件格式可以是properties文件或者yaml文件。在配置文件中,可以设置各种属性和参数,用于配置应用程序的行为。\[3\] 以上是关于SpringBoot的简要介绍和使用方法的说明。如果您有具体的问题或者需要更详细的信息,请提供更多的上下文,我将尽力为您解答。 #### 引用[.reference_title] - *1* [SpringBoot的基本使用](https://blog.csdn.net/weixin_52574640/article/details/126462910)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringBoot使用](https://blog.csdn.net/weixin_45427945/article/details/131138698)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值