8 分钟阅读时长
学习 springboot 框架,就是学习如何使用它的注解。
spring boot 注解及用例
- @Bean
“@Bean” 是类似于 XML 标记的方法级注释。当您声明此注解时,Java 会创建一个具有方法名的 Bean,并将其注册到 BeanFactory。
@Bean
public ExampleBean exampleBean() {
return new ExampleBean();
}
- @Springbootapplication
“@SpringBootApplication”注释会触发自动配置和组件扫描。它结合了三个批注:@Configuration、@ComponentScan 和@EnabeAutoConfiguration。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyClass {
public static void main(String[] args) {
SpringApplication.run(MyClass.class, args);
}
}
- @Configuration
“@Configuration”是一个基于类的注释,它指示类中一个或多个 Bean 方法的定义。一旦 Sprint 容器遇到此注释,它就可以处理这些弹簧 Bean,以便在运行时生成 Bean 定义和服务请求。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConfigClass {
@Bean
public MyBean mybean() {
return new MyBean();
}
}
- @ComponentScan
您可以将“@ComponentScan”注释与“@Configuration”注释结合使用,以定义需要程序扫描的组件。此注释中有几个参数。如果未指定任何参数,框架将使用子包扫描当前包。您可以使用“基本包”参数来定义要扫描的特定包。
package TestPackage;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "TestPackage")
public class TestClass {
}
- @EnableAutoconfiguration
此注释允许您根据自己的要求自动配置程序。框架根据程序和类路径中包含的 jar 来决定此自动配置。例如,假设您添加了“tomcat 嵌入式.jar”文件,如果没有针对其相关工厂 Bean 的显式声明,它将自动配置 TomcatServletWeb 服务器工厂。使用“排除”和“排除类名”参数。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@EnableAutoConfiguration
public class TestClass {
public static void main(String[] args) {
SpringApplication.run(TestClass.class, args);
}
}
- @RequestMapping
“@RequestMapping”注释用于将 HTTP 请求映射到弹簧启动应用程序中的 REST 和 MVC 控制器方法。可以将其应用于控制器中的类级别或方法级别。此外,您可以使用注释中的值列表声明多个请求映射。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ControllerClass {
@ResponseBody
@RequestMapping("/cart")
public String getCart() {
return "this is the cart!";
}
@ResponseBody
@RequestMapping("/catalogue")
public String getCatalogue() {
return "this is the catalogue";
}
}
- @GetMapping
“@GetMapping”是“@RequestMapping(method = RequestMethod.GET)”注释的快捷方式,用于处理与指定 URL 对应的 HTTP GET 请求。以下类使用“@RestController”注释来指示它可以处理 Web 请求。“@GetMapping”将 /hello 映射到 hello() 方法
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/hello")
public String hello() {
return "Hello Spring Boot!";
}
}
- @PostMapping
“@PostMapping”是“@RequestMapping(method = RequestMethod.POST)”注释的快捷方式,用于处理与指定 URL 对应的 HTTP GET 请求。以下类使用“@RestController”注释来指示它可以处理 Web 请求。“@PostMapping”将 /hello 映射到 hello() 方法
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@PostMapping("/hello")
public String hello() {
return "Hello Spring Boot!";
}
}
- @RequestParam
“@RequestParam”注解允许提取输入查询参数、表单数据等。例如,假设您有一个端点/API/book,它接受一个名为 id 的查询字符串参数。然后,您可以使用 @RequestParam 注解以以下方式指定该参数。
@GetMapping("/api/book")
@ResponseBody
public String getBook(@RequestParam String id) {
return "Book ID: " + id;
}
- @PathVariable
“@PathVariable”注解允许从请求地址中提取查询参数等。例如,假设您有一个端点/API/book/1234,它接受一个名为 id 的动态地址字符串参数。然后,您可以使用 @PathVariable 注解以获取该参数。
@GetMapping("/api/book/{id}")
public String getBookForId(@PathVariable Integer id) {
return "Book ID: " + id;
}
- @Service
@Service 是一个类级注释,用于指示该类是定义业务逻辑的服务类。例如,下面的 @Service 注释表明 BankService 是一个提供银行服务的服务类。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BankService {
private final BankInfo bankInfo;
@Autowired
public BankService(BankInfo bankInfo) {
this.bankInfo = bankInfo;
}
}
- @Component
此注解允许框架自动检测组件类,而无需编写任何显式代码。Spring 框架扫描具有@component 的类,初始化它们,并注入所需的依赖项。
import org.springframework.stereotype.Component;
@Component
public class TestComponentAnnotation {
public int multiply(int x, int y) {
return x * y;
}
}
- @Repository
“@Repository”是“@Component”注释的专用版本。它指示该类是一个存储库,其中包含数据存储和其他操作,如更新、删除、搜索和检索对象上的数据。
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.howtodoinjava.demo.model.BookEntity;
@Repository
public interface BookRepository extends JpaRepository<BookEntity, Long>
{
}
- @Controller
这种基于类的注释也是“@Component”注释的特化,将类标记为控制器。它通常与带有@RequestMapping 注释的处理程序方法结合使用,并与 Spring MVC 应用程序一起使用。Spring 使用此注释扫描这些类,并捕获@RequestMapping 注释。下面是其用法的示例。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
@RequestMapping("/hello")
public String hello()
{
return "Hello Spring!";
}
}
- @Autowired
“@Autowired”注释可以在构造函数、设置器方法、属性或具有多个参数的方法上自动连接 Bean。在 setter 方法上使用@Autowired 注释时,可以消除 XML 配置文件中的<属性> 标记。
import org.springframework.beans.factory.annotation.Autowired;
public class Product {
private Product product;
@Autowired
public void setProduct( Product product ){
this.product = product;
}
public Product getProduct( ) {
return product;
}
}
- @SpringBootTest
顾名思义,@SpringBootTest 注释可用于执行基于 Spring Boot 的测试的测试类。当它加载完整的应用程序上下文时,您可以轻松地将其用于集成测试。
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class DemoTest
{
@Autowired
private DemoController demoController;
@Test
public void contextLoads() throws Exception {
assertThat(demoController).isNotNull();
}
}
- @MockBean
使用此注释,可以在应用程序上下文中指定模拟,并从程序中模拟服务或 REST API 终结点。当您运行应用程序时,Spring 加载应用程序上下文的模拟版本。您可以在类和字段级别指定此注释,并且可以在配置类中指定它们。下面是使用“@MockBean”注释的示例。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductServiceTest {
@Autowired
private ProductService productService;
@MockBean(name="Product")
private Product product;
@Test
public void test(){
when(product.findAll()).thenReturn(Collections.emptyList());
assertTrue(productService.findAll().isEmpty());
}
}
------ 如果文章对你有用,感谢右上角 >>>点赞 | 收藏 <<<