SpringBoot注解详情及方法

Spring Boot 是一个用于构建基于 Spring 框架的应用程序的开源框架。它旨在简化 Spring 应用程序的开发和部署过程,提供了一套工具和约定,使得构建和运行 Spring 应用程序变得更加容易。以下是注解及其方法解读:

1.@SpringBootApplication:

        用于标识主应用程序类,通常放在应用程序的入口类上,它包含了@Configuration@EnableAutoConfiguration 和 @ComponentScan 注解。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

        在这个示例中,@SpringBootApplication注解标识了DemoApplication类作为Spring Boot应用程序的入口点。SpringApplication.run()方法启动了Spring Boot应用程序。@SpringBootApplication注解实际上包含了多个注解的功能,包括@Configuration、@EnableAutoConfiguration和@ComponentScan。

2.@RestController:

        用于标识控制器类,表示该类中的所有方法返回的数据都将直接写入 HTTP 响应体中,通常用于构建 RESTful API。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
}

        在这个示例中,@RestController注解标识了HelloController类作为一个RESTful API的控制器。@GetMapping注解用于将HTTP GET请求映射到hello()方法上,并且该方法返回的字符串将直接作为HTTP响应的内容返回给客户端。

3. @Service:

        用于标识服务类,通常放在业务逻辑层的类上,表示该类提供业务逻辑处理。

import org.springframework.stereotype.Service;

@Service
public class UserService {

    public String getUserDetails(Long userId) {
        // 这里可以包含具体的业务逻辑
        return "User details for user id " + userId;
    }
}

        在这个示例中,@Service注解标识了UserService类作为业务逻辑层的组件。通过使用@Service注解,Spring Boot会自动将UserService类注册为Spring上下文中的一个bean,并且可以通过@Autowired注解在其他组件中进行注入和使用。

4.@Repository:

        用于标识数据访问层的类,通常与持久化相关的操作放在这个类上。

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
    // 这里可以定义特定的数据访问方法
}

        在这个示例中,@Repository注解标识了UserRepository接口作为数据访问层的组件。通过使用@Repository注解,Spring Boot会自动将UserRepository接口注册为Spring上下文中的一个bean,并且可以在服务层或控制器层中进行注入和使用。

5.@Autowired:

        用于自动装配 bean,可以用在字段、构造器、方法上,Spring Boot 会自动注入符合类型的 bean。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public String getUserDetails(Long userId) {
        User user = userRepository.findById(userId).orElse(null);
        if (user != null) {
            return "User details for user id " + userId + ": " + user.toString();
        } else {
            return "User not found for user id " + userId;
        }
    }
}

        在这个示例中,@Autowired注解标识了UserService类的构造函数,表明UserService需要依赖注入一个UserRepository组件。通过使用@Autowired注解,Spring Boot会自动在Spring上下文中查找一个UserRepository类型的bean,并将其注入到UserService中。

6.@Configuration:

        用于定义配置类,通常与@Bean注解一起使用,用于定义 bean 对象。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig {

    @Bean
    public UserService userService(UserRepository userRepository) {
        return new UserService(userRepository);
    }

    @Bean
    public UserRepository userRepository() {
        return new UserRepositoryImpl();
    }
}

        在这个示例中,@Configuration注解标识了MyConfig类作为Spring应用程序上下文的配置类。通过使用@Bean注解,MyConfig类定义了两个bean:一个UserService和一个UserRepository。这些bean可以在整个应用程序中进行注入和使用。

7.@RequestMapping:

        用于映射 HTTP 请求到控制器的处理方法上,用于定义请求的 URL 和处理方法的关系。

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@RestController
public class HelloController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String sayHello(@RequestParam String name) {
        return "Hello, " + name + "!";
    }
}

        在这个示例中,@RequestMapping注解标识了HelloController类中的sayHello方法。这个方法将处理HTTP GET请求,并且映射到路径"/hello"。同时,它接受一个名为name的请求参数,并将其用于构造返回的字符串。

8.@Component:

        用于标识组件类,通常作为父注解,用于表示一个受 Spring 管理的组件。

import org.springframework.stereotype.Component;

@Component
public class MyComponent {
    
    public void doSomething() {
        System.out.println("Doing something...");
    }
}

        在这个示例中,@Component注解标识了MyComponent类作为一个Spring组件。这意味着Spring Boot会自动扫描并将MyComponent类实例化为一个bean,并将其纳入到Spring应用程序上下文中。

9.@Value:

        用于注入属性值,可以将配置文件中的属性值注入到类的字段或方法参数中。

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {

    @Value("${myapp.message}")
    private String message;

    public void showMessage() {
        System.out.println("Message: " + message);
    }
}

        在这个示例中,@Value注解用于将名为myapp.message的属性值注入到MyComponent类的message字段中。这个属性值可以在应用程序的配置文件(如application.properties或application.yml)中进行配置。

        例如,在application.properties文件中可以添加如下配置:

myapp.message=Hello from the application

10.@Qualifier:

        用于指定注入的 bean 的名称,通常与@Autowired一起使用,用于指定具体的注入对象。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class MyService {
    
    private MyRepository repository;

    @Autowired
    public MyService(@Qualifier("myRepositoryImpl") MyRepository repository) {
        this.repository = repository;
    }

    // other methods
}

        在这个示例中,@Qualifier("myRepositoryImpl")注解用于指定要注入的bean的限定符为"myRepositoryImpl",这样Spring会找到具有相应限定符的bean进行注入。

11.@ConfigurationProperties:

        用于将配置文件中的属性值绑定到一个类上,通常用于批量注入配置属性。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
    private String appName;
    private String appVersion;

    // Getters and setters
    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public String getAppVersion() {
        return appVersion;
    }

    public void setAppVersion(String appVersion) {
        this.appVersion = appVersion;
    }
}

        myapp.appName=MyApp
myapp.appVersion=1.0

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {
    
    private final MyAppProperties myAppProperties;

    @Autowired
    public MyComponent(MyAppProperties myAppProperties) {
        this.myAppProperties = myAppProperties;
    }

    public void showAppInfo() {
        System.out.println("App Name: " + myAppProperties.getAppName());
        System.out.println("App Version: " + myAppProperties.getAppVersion());
    }
}

        @ConfigurationProperties注解的作用是将配置文件中的属性值映射到JavaBean中,使得开发者可以方便地统一管理配置属性,并且可以通过类型安全的方式在应用程序中使用这些属性值。这样的注解可以帮助开发者更加方便地进行配置管理,提高代码的可维护性和灵活性。

12.@Scheduled:

         用于标识定时任务方法,指定方法定时执行的时间规则。

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyScheduledTask {

    @Scheduled(fixedRate = 5000) // 每隔5秒执行一次
    public void myScheduledMethod() {
        System.out.println("Executing scheduled task...");
        // 其他任务逻辑
    }
}

        在这个示例中,MyScheduledTask类中的myScheduledMethod()方法被@Scheduled注解标记为定时任务。通过设置fixedRate属性为5000,表示这个方法会每隔5秒执行一次。

13.@EnableScheduling:

        用于启用定时任务的支持。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class MyApplication {

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

        然后,在一个组件类中使用@Scheduled注解来标记定时任务的方法

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyScheduledTask {

    @Scheduled(fixedRate = 5000) // 每隔5秒执行一次
    public void myScheduledMethod() {
        System.out.println("Executing scheduled task...");
        // 其他任务逻辑
    }
}

        在这个示例中,@EnableScheduling注解启用了Spring的计划任务功能,而@Scheduled注解标记了一个定时任务的方法。这样就可以在Spring Boot应用程序中方便地创建和执行定时任务。

14.@Transactional:

        用于标识事务方法,指定方法需要在事务中执行。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MyService {

    @Autowired
    private MyRepository myRepository;

    @Transactional
    public void myTransactionalMethod() {
        // 事务处理逻辑
        myRepository.save(new MyEntity("test"));
        // 其他事务处理逻辑
    }
}

        在这个示例中,MyService类中的myTransactionalMethod()方法被@Transactional注解标记为事务处理方法。在这个方法中,通过调用myRepository的save方法来保存一个实体对象。由于这个方法被@Transactional注解标记,所以这个方法会在一个事务中执行,当方法执行结束时,如果没有发生异常,事务会自动提交。

15.@EnableCaching:

        用于启用 Spring 的缓存支持。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class MyApplication {

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

        然后,在需要使用缓存的方法上添加@Cacheable注解

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Cacheable("myCache")
    public String myCachingMethod(String key) {
        // 从数据库或其他数据源中获取数据
        String value = getValueFromDataSource(key);
        return value;
    }
}

        在这个示例中,MyService类中的myCachingMethod()方法被@Cacheable注解标记为需要缓存的方法。@Cacheable注解的参数指定了缓存的名称,这个名称可以在配置文件中进行配置。

  • 8
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值