用spring boot写出hello world
时间: 2024-09-14 17:05:03 浏览: 50
在Spring Boot中创建一个简单的"Hello World"应用非常直观,主要是通过一个配置类来初始化Spring应用。以下是基础步骤:
1. 创建一个新的Spring Boot项目,选择"Maven"或"Gradle"作为构建工具。
2. 添加主程序类,通常命名为`Application`或`DemoApplication`。
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
@Bean
public HelloBean helloBean() {
return new HelloBean();
}
}
```
在这里,`@SpringBootApplication`注解表示这是一个Spring Boot应用程序,`main`方法启动应用,`HelloBean`是一个简单示例bean,用于演示如何注入和访问。
3. 创建一个实现了`MessageSourceAware`接口的简单bean,例如`HelloBean`:
```java
@Component
public class HelloBean implements MessageSourceAware {
private final MessageSource messageSource;
public HelloBean(MessageSource messageSource) {
this.messageSource = messageSource;
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
public String getMessage() {
return messageSource.getMessage("hello", null, LocaleContextHolder.getLocale());
}
}
```
然后,添加`messages.properties`资源文件,如`src/main/resources/messages.properties`:
```properties
hello=Hello, %s!
```
当运行应用,访问`/hello`(假设端口为8080),将显示"Hello, World!"。
阅读全文
相关推荐


















