Java 常用注解

一、较不熟悉
1、@MappedJdbcTypes(JdbcType.VARCHAR)
MyBatis 框架中的一个注解,用于指定某个字段或方法参数与数据库中的 JDBC 类型之间的映射关系。通常作用在实体类属性或者参数上。
如下标识username字段映射到数据库中的VARCHAR属性。
public interface UserMapper {
@Select(“SELECT * FROM user WHERE username = #{username}”)
User getUserByUsername(@Param(“username”) @MappedJdbcTypes(JdbcType.VARCHAR) String username);
}

2、@Import({Annotation4.class})
Spring Framework 中的一个注解,用于导入配置类或组件,将它们加入到 Spring 的应用上下文中。当你使用 @Import 注解时,你告诉 Spring 容器去加载并注册指定的类。这通常用于以下情况:
(1)、导入配置类:当你想要将另一个配置类中的 @Bean 方法定义的 bean 导入到当前配置类中时。
(2)、导入组件:导入一些特殊的组件,这些组件可能不是通过 @Component、@Service、@Repository 或 @Controller 注解自动扫描的。
(3)、导入 ImportSelector 或 ImportBeanDefinitionRegistrar:这些是更高级的用法,允许你基于某些条件动态地导入配置类或 bean 定义。
3、@Profile
是Spring Framework 中的注解,用于指示某个组件在特定的环境下生效。
注:
运行时使用哪个profile由spring.profiles.active控制,常用以下2种方式:配置文件方式、命令行方式。
配置文件application.properties
spring.profiles.active=dev
或启动命令指定环境:
java -jar xxx.jar --spring.profiles.active=dev
@Configuration
@Profile(“dev”)
public class DevConfig {
// … Bean definitions for development environment …
}

@Configuration
@Profile(“prod”)
public class ProdConfig {
// … Bean definitions for production environment …
}

4、@PropertySource
指定一个或多个属性文件的位置,这些属性文件包含配置信息,可以被 @Value 注解引用,或者通过 Environment 抽象访问。
如下:引入application_1.properties配置文件,之后可以将application_1.properties配置文件中的app.name通过@Value的方式注入到appName中。
@Configuration
@PropertySource(“classpath:application_1.properties”)
public class AppConfig {

@Value("${app.name}")  
private String appName;  

// ... other bean definitions ...  

}
5、@ConditionalOnClass(name = {“”})
如:@ConditionalOnClass(name = {“springfox.documentation.spring.web.SpringfoxWebMvcConfiguration”})

是 Spring Boot 中的一个条件注解,用于在类路径(classpath)上检查指定的类是否存在。只有当指定的类存在时,带有此注解的组件(如配置类、bean 等)才会被注册到 Spring 应用上下文中。

若是和@Import等注解一起使用时,如果@ConditionalOnClass指定的类不存在,则@Import不能注入成功。若条件成立时则可以注入成功。

6、@ConditionalOnWebApplication

是 Spring Boot 的一个条件注解,用于确定当前应用是否是一个 Web 应用。如果不是 Web 应用(例如,它可能是一个命令行应用),那么这些带有 @ConditionalOnWebApplication 注解的配置类就不会被加载。

7、@SpringBootConfiguration
注解用于标记一个类为配置类,它继承自@Configuration注解,表示该类是一个配置类,可以用来定义bean、配置属性等。

8、@EnableAutoConfiguration
用于启用自动配置功能,它告诉Spring Boot根据项目中的依赖关系自动配置bean。例如,如果项目中包含了MySQL驱动,那么Spring Boot会自动配置一个DataSource bean,用于连接MySQL数据库。

9、@AliasFor
是 Spring Framework 中的一个注解,它用于在自定义注解中创建一个属性的别名,通常与复合注解(如 @SpringBootApplication)一起使用,以确保属性的值能够正确地传播到它们所代表的注解中。

如下:当使用SpringBootApplication注解且指定scanBasePackages参数时。相当于引用ComponentScan注解赋值给basePackageClasses属性。
public @interface SpringBootApplication {
@AliasFor(
annotation = ComponentScan.class,
attribute = “basePackageClasses”
)
String[] scanBasePackages() default {};
}

如下:当使用SpringBootApplication注解且指定proxyBeanMethods参数时。相当于引用Configuration注解的proxyBeanMethods属性,赋予了相同的值。
public @interface SpringBootApplication {
@AliasFor(
annotation = Configuration.class
)
boolean proxyBeanMethods() default true;
}

10、@ConfigurationProperties(prefix = “mqtt”)
用来定义从外部配置源(比如 properties 或 YAML 文件)绑定属性到一个配置类上。通常需要通过@EnableConfigurationProperties(当前类.class)将当前的配置类加载到spring容器中。如果当前类已经通过@Component被扫描加载到spring容器了,则不在需要@EnableConfigurationProperties(当前类.class)加载。
application.properties
mqtt.host=localhost
mqtt.port=1883

Java
@ConfigurationProperties(prefix = “mqtt”)
public class Annotation1 {
private String host;
private int port;
}

11、@EnableConfigurationProperties(Annotation1.class)
将指定的类加载到容器中,通常是@ConfigurationProperties注解修饰的类。如果该类已经被扫描加载到容器中了,则当前注解也可以不要。

12、@Primary
Spring Framework 中的一个注解,它用于在存在多个同类型的 bean 时,指定一个首选的 bean,以用于自动装配。当然如果想明确指定了想要使用的 bean(例如,通过 @Qualifier 注解)

如下:Spring 会选择 BeanB,因为它带有 @Primary 注解。
@Component
public class BeanA implements MyInterface {
// …
}

@Component
@Primary
public class BeanB implements MyInterface {
// …
}

使用BeanB ,因为
@Autowired
private MyInterface myInterface;
13、@Qualifier
容器中有多个相同类型的 beans 存在时。通过 @Qualifier,你可以指定要注入的确切 bean。
public interface MessageService {
String getMessage();
}

@Component(“helloMessageService”)
public class HelloMessageService implements MessageService {
@Override
public String getMessage() {
return “Hello World!”;
}
}

@Component(“goodbyeMessageService”)
public class GoodbyeMessageService implements MessageService {
@Override
public String getMessage() {
return “Goodbye World!”;
}
}

// 使用@Qualifier(“helloMessageService”) 告诉容器到底使用哪一个bean
@Autowired
@Qualifier(“helloMessageService”)
private MessageService messageService;
14、@ControllerAdvice
Spring 框架中用于全局处理控制器层异常的注解。它通常与 @ExceptionHandler、@InitBinder 和 @ModelAttribute 注解一起使用,以提供全局的异常处理、数据绑定和数据预处理逻辑。
使用参考下面15的@ExceptionHandler示例。
15、@ExceptionHandler(Exception.class)
用于处理由控制器方法抛出的异常。开发者可以对特定的异常类型定义自定义的处理逻辑,而不是依赖于默认的异常处理机制。需要放在@ControllerAdvice注解的类中使用。如果没有执行异常类型,则是错误的定义,方法不会生效。

示例:当controller中抛出任何异常都走此方法处理。(实际中通过 @ExceptionHandler(value = 自定义异常.class)比较常用)
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(value = Exception.class)
public ResponseEntity<Object> handleAllExceptions(Exception ex, HttpServletRequest request, WebRequest webRequest) {
    // 获取异常类信息
    Class<? extends Throwable> exceptionClass = ex.getClass();
    System.out.println("异常类型的名称: " + exceptionClass.getName());

    // 获取请求参数(get请求或post-form)
    Enumeration<String> paramNames = request.getParameterNames();
    StringBuilder paramsBuilder = new StringBuilder();
    while (paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        String paramValue = request.getParameter(paramName);
  paramsBuilder.append(paramName).append("=").append(paramValue).append("&");
    }
    String params = paramsBuilder.toString();
    if (params.length() > 0) {
        params = params.substring(0, params.length() - 1); // 移除末尾的 '&'
    }
    System.out.println("http请求参数: " + params);

    // 获取堆栈跟踪元素数组
    StackTraceElement[] stackTraceElements = ex.getStackTrace();
    if (stackTraceElements.length > 0) {
        StackTraceElement element 
  • 23
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java常用注解及作用 1. @Override:标注在方法上,表示该方法覆盖了父类中的方法。 2. @Deprecated:标注在方法、类、字段上,表示该方法、类、字段已经过时,不推荐使用。 3. @SuppressWarnings:标注在类、方法、字段上,用于抑制编译器的警告信息。 4. @FunctionalInterface:标注在接口上,用于指定该接口是函数式接口。 5. @SafeVarargs:标注在方法上,用于表示该方法使用了可变参数,但是不会出现类型不安全的情况。 6. @Nullable:标注在参数、字段、方法返回值上,用于表示该参数、字段、方法返回值可能为null。 7. @NonNull:标注在参数、字段、方法返回值上,用于表示该参数、字段、方法返回值不可能为null。 8. @Resource:标注在字段、setter方法、构造方法上,用于注入依赖对象。 9. @Autowired:标注在字段、setter方法、构造方法上,用于注入依赖对象。 10. @Service:标注在类上,表示该类是一个服务类。 11. @Repository:标注在类上,表示该类是一个数据访问对象。 12. @Controller:标注在类上,表示该类是一个控制器。 13. @RequestMapping:标注在方法上,用于指定请求路径。 14. @PathVariable:标注在方法参数上,用于获取请求路径中的变量。 15. @RequestBody:标注在方法参数上,用于获取请求体中的数据。 16. @ResponseBody:标注在方法上,用于将方法返回值转换成指定的格式并返回给客户端。 17. @Transactional:标注在方法上,表示该方法需要在事务中执行。 18. @Aspect:标注在切面类上,用于指定该类是一个切面类。 19. @Pointcut:标注在方法上,用于指定切入点。 20. @Before:标注在方法上,表示该方法是一个前置通知。 21. @AfterReturning:标注在方法上,表示该方法是一个后置通知。 22. @AfterThrowing:标注在方法上,表示该方法是一个异常通知。 23. @Around:标注在方法上,表示该方法是一个环绕通知。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值