1、启动Spring Boot 的一种方式
服务启动类
package com.npc.rest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
/**
- Frozen
- 2020-1-29
*/
/**
- 之前用户使用的是3个注解注解他们的main类。
- 分别是@Configuration,@EnableAutoConfiguration,@ComponentScan。
- 由于这些注解一般都是一起使用,
- spring boot提供了一个统一的注解@SpringBootApplication。
- @SpringBootApplication =
- (默认属性)@Configuration + @EnableAutoConfiguration + @ComponentScan。
- 分开解释@Configuration,@EnableAutoConfiguration,@ComponentScan。
- 1、@Configuration:提到@Configuration就要提到他的搭档@Bean。
- 使用这两个注解就可以创建一个简单的spring配置类,可以用来替代相应的xml配置文件。
-
<bean id = "car" class="com.test.Frozen"> -
<property name="red" ref = "red"></property> -
</bean> -
<bean id = "ant" class="com.test.RedAnt"></bean> - 相当于:
- @Configuration
- public class Conf {
-
@Bean -
public Car car() { -
Frozen item = new Frozen(); -
item.setRed(redant()); -
return item; -
} -
@Bean -
public RedAnt redant() { -
return new RedAnt(); -
} - }
- @Configuration的注解类标识这个类可以使用Spring
- IoC容器作为bean定义的来源。
- @Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,
- 该对象应该被注册为在Spring应用程序上下文中的bean。
- 2、@EnableAutoConfiguration:
- 能够自动配置spring的上下文,试图猜测和配置你想要的bean类,
- 通常会自动根据你的类路径和你的bean定义自动配置。
- 3、@ComponentScan:
- 会自动扫描指定包下的全部标有@Component的类,并注册成bean,
- 当然包括@Component下的子注解@Service,@Repository,@Controller。
*/
@SpringBootApplication
@ImportResource(value = {“classpath:css-npc-web.xml”})//引入其他资源,加不加依情况而定
public class FrozenApplication {
public static void main(String[] args) {
SpringApplication.run(FrozenApplication.class, args);
}
}
方法实现类
package com.npc.rest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
- Frozen
- 2020年1月29日17:03:31
- 服务实现类
*/
/**
- @RestController = @Controller + @ResponseBody组成,
- 等号右边两位同志简单介绍两句,就明白我们@RestController的意义了:
- @Controller
- 将当前修饰的类注入SpringBoot IOC容器,
- 使得从该类所在的项目跑起来的过程中,这个类就被实例化。
- @ResponseBody 它的作用简短截说就是指该类中所有的API接口返回的数据,
- 会以Json字符串的形式返回给客户端
*/
@RestController
@RequestMapping("/redant")
@Slf4j
public class FrozenTest {
@GetMapping("/hoyl")
public void genToken() {
System.err.println(“时间2020年1月29日16:58:15,测试数据”);
for (int i = 0; i < 10; i++) {
Date date = new Date();
long times = date.getTime();
System.err.println(“时间测试数据:”+times);
log.info(“时间测试数据:”+times);
}
}
}
【PS:关于 @ Slf4j我有话说】
1、@ Slf4j这玩意是做什么的?
答:如果不想每次都写private final Logger logger = LoggerFactory.getLogger(当前类名.class); 可以用注解@Slf4j;
你想用它,你得加入依赖包:
本文深入解析SpringBoot启动方式及核心注解@SpringBootApplication的功能,包括@Configuration、@EnableAutoConfiguration和@ComponentScan的作用,以及@RestController注解如何简化RESTful API开发。

被折叠的 条评论
为什么被折叠?



