常用注解
目录
@SuppressWarnings
用于抑制编译器产生警告信息。
| 类型 | 说明 |
|---|---|
| @SuppressWarnings(“unchecked”) | 抑制未检查的转化,例如集合没有指定类型的警告 |
| @SuppressWarnings(“unused”) | 抑制未使用的变量的警告 |
| @SuppressWarnings(“resource”) | 抑制与使用Closeable类型资源相关的警告 |
| @SuppressWarnings(“path”) | 抑制在类路径,原文件路径中有不存在的路径的警告 |
| @SuppressWarnings(“path”) | 抑制在类路径,原文件路径中有不存在的路径的警告 |
| @SuppressWarnings("deprecation") | 抑制使用了某些不赞成使用的类和方法的警告 |
| @SuppressWarnings("fallthrough") | 抑制switch语句执行到底没有break关键字的警告 |
| @SuppressWarnings("serial") | 抑制某类实现Serializable,但是没有定义serialVersionUID,这个需要但是不必须的字段的警告 |
| @SuppressWarnings("rawtypes") | 抑制没有传递带有泛型的参数的警告 |
| @SuppressWarnings("all") | 抑制全部类型的警告 |
@Bean
@Bean用于标记工厂方法,用于实例化 Spring Bean:
@Bean
Engine engine() {
return new Engine();
}
生成的 Bean 的名称与工厂方法的名称相同。如果想使用不同的名称,可以使用此注解的 name 或 value 参数(value 是 name 的别名):
@Bean("engine")
Engine getEngine() {
return new Engine();
}
注意,所有注解为@Bean的方法必须位于@Configuration类中。
@Scope
源码走一波
/**
* When used as a type-level annotation in conjunction with
* {@link org.springframework.stereotype.Component @Component},
* {@code @Scope} indicates the name of a scope to use for instances of
* the annotated type.
*
* <p>When used as a method-level annotation in conjunction with
* {@link Bean @Bean}, {@code @Scope} indicates the name of a scope to use
* for the instance returned from the method.
*
* <p><b>NOTE:</b> {@code @Scope} annotations are only introspected on the
* concrete bean class (for annotated components) or the factory method
* (for {@code @Bean} methods). In contrast to XML bean definitions,
* there is no notion of bean definition inheritance, and inheritance
* hierarchies at the class level are irrelevant for metadata purposes.
*
* <p>In this context, <em>scope</em> means the lifecycle of an instance,
* such as {@code singleton}, {@code prototype}, and so forth. Scopes
* provided out of the box in Spring may be referred to using the
* {@code SCOPE_*} constants available in the {@link ConfigurableBeanFactory}
* and {@code WebApplicationContext} interfaces.
*
* <p>To register additional custom scopes, see
* {@link org.springframework.beans.factory.config.CustomScopeConfigurer
* CustomScopeConfigurer}.
*
* @author Mark Fisher
* @author Chris Beams
* @author Sam Brannen
* @since 2.5
* @see org.springframework.stereotype.Component
* @see org.springframework.context.annotation.Bean
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {
/**
* Alias for {@link #scopeName}.
* @see #scopeName
*/
@AliasFor("scopeName")
String value() default "";
/**
* Specifies the name of the scope to use for the annotated component/bean.
* <p>Defaults to an empty string ({@code ""}) which implies
* {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}.
* @since 4.2
* @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
* @see ConfigurableBeanFactory#SCOPE_SINGLETON
* @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
* @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
* @see #value
*/
@AliasFor("value")
String scopeName() default "";
/**
* Specifies whether a component should be configured as a scoped proxy
* and if so, whether the proxy should be interface-based or subclass-based.
* <p>Defaults to {@link ScopedProxyMode#DEFAULT}, which typically indicates
* that no scoped proxy should be created unless a different default
* has been configured at the component-scan instruction level.
* <p>Analogous to {@code <aop:scoped-proxy/>} support in Spring XML.
* @see ScopedProxyMode
*/
ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}
大致理解:
当与 @Component 一起用作类型级批注时,@Scope 指示用于批注类型实例的作用域的名称。当与 @Bean 一起用作方法级批注时,@Scope 指示要用于从方法返回的实例的作用域的名称。
注意:@Scope注释仅在 concrete bean 类(对于带注释的元件)或工厂方法(对于@Bean方法)上进行内省。与 XML Bean 定义相比,没有 Bean 定义继承的概念,类级别的继承层次结构与元数据无关。
在此上下文中,范围是指实例的生命周期,例如单例、原型等。Spring 中开箱即用的范围可以使用 ConfigurableBeanFactory 和 WebApplicationContext 接口中提供的SCOPE_常量来引用。
常用于更改Spring中Bean的作用域。
单例:singleton
Spring中Bean的默认作用域。
多例:prototype
prototype非常适合有状态的Bean,每个实例都可以保存独立于其他实例的数据。
常用
ConfigurableBeanFactory.SCOPE_PROTOTYPE指定。
public class TestScope {
@NoArgsConstructor
public class ScopeClass {
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public ScopeClass scopeClass() {
return new ScopeClass();
}
}
HTTP请求:request
每个HTTP请求时创建该Bean的新实例。
注意:被request标记的bean不能在多个请求之间被共享
public class TestScope {
@NoArgsConstructor
public class ScopeClass {
}
// 方式一
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public ScopeClass scopeClass() {
return new ScopeClass();
}
// 方式二
@Bean
@RequestScope
public ScopeClass scopeClassRequest() {
return new ScopeClass();
}
}
会话:session
每个HTTP session创建Bean的实例
注意:可以理解为一个用户第一次访问时创建,关闭浏览器时回收。
public class TestScope {
@NoArgsConstructor
public class ScopeClass {
}
// 方式一
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public ScopeClass scopeClass() {
return new ScopeClass();
}
// 方式二
@Bean
@SessionScope
public ScopeClass scopeClassRequest() {
return new ScopeClass();
}
}
@Primary
Spring Bean 有时需要多个实现类实现同一个接口,在这种情况下,注入将不会成功,因为 Spring 不知道需要注入哪个 Bean。 这种情况下可以将最常用的 Bean 标记为@Primary,它将在未标记@Qualifier的注入点上被选中,即被@Primary标记的 Bean 会作为默认类型注入。
@Component
@Primary
class Car implements Vehicle {}
@Component
class Bike implements Vehicle {}
@Component
class Driver {
@Autowired
Vehicle vehicle;
}
@Component
class Biker {
@Autowired
@Qualifier("bike")
Vehicle vehicle;
}
@DependsOn
可以使用此注解让 Spring 在注解的 Bean 之前初始化其他 Bean。通常情况下,这种行为是自动进行的,基于 Bean 之间的显式依赖关系。
只有当依赖关系是隐式的,例如 JDBC 驱动加载或静态变量初始化时,才需要此注解。
可以在依赖类上使用@DependsOn来指定依赖 Bean 的名称。注解的 value 参数需要一个包含依赖 Bean 名称的数组:
@DependsOn("engine")
class Car implements Vehicle {}
或者,如果我们使用 @Bean 注解定义 Bean,那么就应该在工厂方法上使用 @DependsOn 注解:
@Bean
@DependsOn("fuel")
Engine engine() {
return new Engine();
}
@Lazy
当我们希望延迟初始化 Bean 时,可以使用@Lazy注解。默认情况下,Spring 在 Application Context 启动时会立即创建所有 Singleton(单例)Bean。
不过,在某些情况下,我们需要在使用时创建 Bean,而不是在应用启动时。
这个注解会根据具体标注位置而有不同的表现,可以用在如下位置:
@Bean注解的 Bean 工厂方法,可以延迟方法调用(从而延迟 Bean 的创建)。@Configuration类,包含的 @Bean 方法都将受到影响@Component类,而该组件类不是 @Configuration 类,则该 Bean 将被延迟地初始化@Autowired构造函数、Setter 方法或字段,用于延迟地(通过代理)加载依赖本身
该注解有一个名为 value 的参数,默认值为 true。它可以覆盖默认行为。
例如,当全局设置为懒加载(lazy)时,可以标记要立即加载的 Bean,或者在使用@Lazy标记的@Configuration类中,配置特定的@Bean 方法以进行立即加载:
@Configuration
@Lazy
class VehicleFactoryConfig {
@Bean
@Lazy(false) // 立即加载
Engine engine() {
return new Engine();
}
}
