首页 > 其他分享 >15 Spring核心注释示例

15 Spring核心注释示例

时间:2023-06-15 15:06:39浏览次数:44  
标签:15 示例 Spring Value 注释 bean public


我们经常将这些称为“Spring核心注释”,我们将在本文中对它们进行审核。

这是所有已知的Spring核心注释的列表。

15 Spring核心注释示例_初始化

@Autowired

我们可以使用  @Autowired 注释  来标记Spring将要解析和注入的依赖关系。我们可以将这个注释与构造函数,setter或字段注入一起使用。

构造函数注入:

@RestController
公共 类 CustomerController {
    私人 CustomerService  customerService ;
 
    @Autowired
    public  CustomerController(CustomerService  customerService){
        这个。customerService  =  customerService ;
    }


 

二传手注射:

进口 组织。弹簧框架。豆子。工厂。注释。自动装配 ;
进口 组织。弹簧框架。网络。绑定。注释。RestController ;


 

@RestController
公共 类 CustomerController {
    私人 CustomerService  customerService ;
 
    @Autowired
    public  void  setCustomerService(CustomerService  customerService){
        这个。customerService  =  customerService ;
    }
}

 

现场注入:

进口 组织。弹簧框架。豆子。工厂。注释。自动装配 ;
进口 组织。弹簧框架。网络。绑定。注释。RestController ;


 

@RestController
公共 类 CustomerController {
    @Autowired
    私人 CustomerService  customerService ;
}

有关更多详细信息,请访问我们关于 @Autowired和  Spring依赖注入指南的文章。

@豆

  •  @Bean 是方法级注释和XML元素的直接模拟。注释支持一些提供的属性,例如init-method,destroy-method,auto-wiring和name。
  • 您可以在带@Bean 注释@Configuration或带  注释的@Component类中使用   注释   。

以下是@Bean方法声明的简单示例  :

进口 组织。弹簧框架。背景。注释。豆 ;
进口 组织。弹簧框架。背景。注释。配置 ;


 


进口 com。公司名称。projectname。客户。客户服务 ;
进口 com。公司名称。projectname。订单。OrderService ;


 


@组态
公共 类 申请 {
 
    @豆
    public  CustomerService  customerService(){
        返回 new  CustomerService();
    }
 
    @豆
    public  OrderService  orderService(){
        返回 新的 OrderService();
    }
}
 


上述配置等效于以下Spring XML:

< beans >
        < bean  id = “customerService”  class = “com.companyname.projectname.CustomerService” />
        < bean  id = “orderService”  class = “com.companyname.projectname.OrderService” />
</ beans >
————————————————


阅读 @Bean 本文中有关注释的  更多信息   Spring @Bean Annotation with Example

@Qualifier

此注释有助于微调基于注释的自动布线。可能存在这样的情况:我们创建多个相同类型的bean,并且只想使用属性连接其中一个bean。这可以使用@Qualifier 注释和   @Autowired 注释来控制  。

示例:考虑使用  EmailService 和  SMSService 类来实现单个   MessageService 接口。

MessageService 为多个消息服务实现创建  接口。

公共 接口 MessageService {
    public  void  sendMsg(String  message);
}
 

接下来,创建实现:   EmailService 和  SMSService。

公共 类 EmailService  实现 MessageService {
 
    public  void  sendMsg(String  message){
         系统。出。println(消息);
    }
}
 

公共 类 SMSService  实现 MessageService {
 
    public  void  sendMsg(String  message){
         系统。出。println(消息);
    }


 

 

是时候看看@Qualifier 注释的用法了  。

公共 接口 MessageProcessor {
    public  void  processMsg(String  message);
}
 
公共 类 MessageProcessorImpl  实现 MessageProcessor {
 
    private  MessageService  messageService ;
 
    //基于setter的DI
    @Autowired
    @Qualifier(“emailService”)
    public  void  setMessageService(MessageService  messageService){
        这个。messageService  =  messageService ;
    }
 
    //基于构造函数的DI
    @Autowired
    public  MessageProcessorImpl(@Qualifier(“emailService”)MessageService  messageService){
        这个。messageService  =  messageService ;
    }
 
    public  void  processMsg(String  message){
        messageService。sendMsg(message);
    }
}


在本文中阅读有关此注释的更多信息:   Spring @Qualifier Annotation示例

@需要

的  @Required 注释是一个方法级注释和施加到bean的setter方法。

此注释仅指示必须将setter方法配置为在配置时使用值依赖注入。

例如,  @Required setter方法标记了我们想要通过XML填充的依赖项:

@需要
void  setColor(String  color){
    这个。color  =  color ;
}
 

< bean  class = “com.javaguides.spring.Car” >
    < property  name = “color”  value = “green”  />
</ bean >
 


 

 

否则,   BeanInitializationException 将被抛出。

@值

Spring  @Value 注释用于为变量和方法参数指定默认值。我们可以使用@Value 注释来读取Spring环境变量以及系统变量  。

Spring  @Value 注释也支持SpEL。让我们看一下使用@Value 注释的一些示例  。

示例:我们可以使用@Value 注释为类属性指定默认值  。

@Value(“默认DBConfiguration”)
private  String  defaultName ;

 

该  @Value 注释参数可以是只有字符串,但春天尝试将其转换为指定的类型。以下代码将正常工作,并将布尔值和整数值分配给变量。

@Value(“$ {java.home}”)
private  String  javaHome ;
 
@Value(“$ {HOME}”)
private  String  homeDir ;
private  int  defaultInt ; 
这演示了Spring   @Value -  Spring Environment Property
@Value(“$ {APP_NAME_NOT_FOUND}”)


 

接下来,使用@Value 注释分配系统变量  。

@Value(“$ {java.home}”)
private  String  javaHome ;

 

春天  @Value  - SpEL

@Value(“#{ systemProperties ['java.home']}”)
private  String  javaHome ;

 

@依赖于取决于

@DependsOn 注释可以强制的Spring IoC容器中的bean,它是由注释之前初始化一个或多个bean   @DependsOn 注释。

所述  @DependsOn 注释可以在直接或间接地注释与任何类使用   @Component 或与所述注解的方法  @Bean

示例:让我们创建   FirstBean 和   SecondBean 类。在此示例中,   SecondBean 在bean之前初始化   FirstBean

公共 类 FirstBean {
 
    @Autowired
    private  SecondBean  secondBean ;
}
 
公共 类 SecondBean {
    public  SecondBean(){
        系统。出。println(“通过Constuctor初始化的SecondBean”);
    }
}


 

基于配置类在Java中声明上述bean。

@组态
public  class  AppConfig {
 
    @Bean(“ firstBean ”)
    @DependsOn(value  = {
        “secondBean”
    })
    公共 FirstBean  firstBean(){
        返回 新的 FirstBean();
    }
 
    @Bean(“secondBean”)
    public  SecondBean  secondBean(){
        返回 new  SecondBean();
    }
}


阅读有关 Spring上@DependsOn注释的更多信息  - @DependsOn注释示例

@懒

默认情况下,Spring IoC容器在应用程序启动时创建并初始化所有单例bean。我们可以通过使用@Lazy 注释来防止单例bean的这种预初始化  。

所述   @Lazy 注释可以在任何类中使用,与直接或间接地注释   @Component 或与所述注解的方法  @Bean

示例:考虑我们有两个bean -  FirstBean 和   SecondBean。在此示例中,我们将FirstBean 使用   @Lazy注释显式加载   。

公共 类 FirstBean {
    public  void  test(){
        系统。出。println(“FirstBean类的方法”);
    }
}
 

公共 类 SecondBean {
    public  void  test(){
        系统。出。println(“SecondBean类的方法”);
    }
}
 

基于配置类在Java中声明上述bean。

@组态
public  class  AppConfig {
 
    @Lazy(value  =  true)
    @豆
    公共 FirstBean  firstBean(){
        返回 新的 FirstBean();
    }
 
    @豆
    public  SecondBean  secondBean(){
        返回 new  SecondBean();
    }
}


我们可以看到,bean  secondBean 由Spring容器初始化,而bean  firstBean 则被显式初始化。

阅读有关 @Lazy  注释的更多信息,  并在 Spring上提供完整的示例  - @Lazy Annotation示例

@抬头

注释的方法   @Lookup 告诉Spring在我们调用它时返回方法返回类型的实例。

有关此注释的详细信息,请参见  Spring @LookUp Annotation

@主

@Primary 当存在多个相同类型的bean时,我们使用它   给bean更高的优先级。

@零件
@主
class  Car  实现 Vehicle {}
 
@零件
class  Bike  实现 Vehicle {}
 
@零件
class  Driver {
    @Autowired
    车辆 车辆 ;
}
 
@零件
class  Biker {
    @Autowired
    @Qualifier(“自行车”)
    车辆 车辆 ;
}
————————————————


Spring上阅读有关此注释的更多信息  - @Primary Annotation示例

@范围

我们使用@Scope 注释来定义类的范围或  @Bean定义。它可以是单例,原型,请求,会话,globalSession或某些自定义范围。  @Component 

例如:

@零件
@Scope(值 =  ConfigurableBeanFactory。SCOPE_SINGLETON)
公共 类 TwitterMessageService  实现 MessageService {
}
 
@零件
@Scope(值 =  ConfigurableBeanFactory。SCOPE_PROTOTYPE)
公共 类 TwitterMessageService  实现 MessageService {
}

Scope注解  春@Scope注解与辛格尔顿范围实例和  春天@Scope注解与原型作用域实例

@轮廓

如果我们希望Spring 只在特定的配置文件处于活动状态时才使用  @Component 类或  @Bean方法,我们可以用它来标记它   @Profile。我们可以使用注释的value参数配置配置文件的名称:

@零件
@Profile(“sportDay”)
class  Bike  实现 Vehicle {}


您可以在此阅读更多关于型材  春型材

@进口

该   @Import 注释指示一个或多个@Configuration类进口。

例如:在基于Java的配置中,Spring提供了  @Import  注释,允许从另一个配置类加载@Bean定义。

公共 类 ConfigA {
 
    @豆
    public  A  a(){
        返回 新的 A();
    }
}
 
@组态
@Import(ConfigA。类)
公共 类 ConfigB {
 
    @豆
    public  B  b(){
        return  new  B();
    }
}
 
————————————————



 

现在,在实例化上下文时,不需要同时指定  ConfigA类和ConfigB类,只需要显式提供ConfigB

阅读有关 Spring @Import Annotation@Import注释的更多信息 。

@ImportResource

Spring提供了一个  @ImportResource 注释,用于将bean从applicationContext.xml文件加载到ApplicationContext中。例如:考虑我们在类路径上有applicationContext.xml Spring bean配置XML文件。

@组态
@ImportResource({ “classpath *:applicationContext.xml” })
公共 类 XmlConfiguration {
}


通过 Spring @ImportResource Annotation的完整示例,阅读有关此注释的更多信息 。

@PropertySource

该   @PropertySource 注释提供了一种方便的声明性机制,用于添加  PropertySource Spring的Eenvironment以与@Configuration类一起使用  。

例如,我们从文件config.properties文件中读取数据库配置,并使用Environment 将这些属性值设置为  DataSourceConfig类。

进口 组织。弹簧框架。豆子。工厂。InitializingBean ;
进口 组织。弹簧框架。豆子。工厂。注释。自动装配 ;
进口 组织。弹簧框架。背景。注释。配置 ;
进口 组织。弹簧框架。背景。注释。PropertySource ;
进口 组织。弹簧框架。核心。ENV。环境 ;
 
@组态
@PropertySource(“classpath:config.properties”)
公共 类 ProperySourceDemo  实现 InitializingBean {
 
    @Autowired
    环境 ENV ;
 
    @覆盖
    public  void  afterPropertiesSet()抛出 Exception {
        setDatabaseConfig();
    }
 
    private  void  setDatabaseConfig(){
        DataSourceConfig  config  =  new  DataSourceConfig();
        配置。setDriver(ENV。的getProperty(“jdbc.driver” ));
        配置。setUrl(ENV。的getProperty(“jdbc.url” ));
        配置。setUsername(ENV。的getProperty(“jdbc.username” ));
        配置。setPassword(ENV。的getProperty(“jdbc.password” ));
        系统。出。的println(配置。的toString());
    }
}


阅读有关 Spring @PropertySource Annotation with Example的此注释的更多信息 。

@PropertySources

我们可以使用此批注指定多个   @PropertySource  配置:

 @PropertySources({
  @PropertySource(“classpath:config.properties”),
  @PropertySource(“classpath:db.properties”)
 })
 public  class  AppConfig {
  // ...
 }

标签:15,示例,Spring,Value,注释,bean,public
From: https://blog.51cto.com/u_16145034/6492473

相关文章

  • springboot 自定义listener 添加环境变量。 抄的springboot项目去掉了一些不用的ja
    1.自定义listener实现 ApplicationListener<ApplicationEnvironmentPreparedEvent>,Ordered(如果要设置优先级可以实现Ordered接口,注意order值越小优先级越高)publicclassMyListenerimplementsApplicationListener<ApplicationEnvironmentPreparedEvent>,Ordered{......
  • ajax请求springboot
    老是忘记ajax请求格式,记录一下吧后面看自己的functionsave(){varURL="/reconciliation/wzglWzMaterilApplicationDetail/saveSupplier";varcc=JSON.stringify({data:"world",p:{pag:0,pageS......
  • springboot项目启动失败之 org.springframework.boot.env.OriginTrackedYamlLoader.cr
    1、检查一下父项目的module的依赖是否,以及版本是否一致。例如<dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version>1.30</version></dependency>2、如何知道自己的org.yaml的版本,可以双击Shift键,输入如图所示,注意划红线的地方就是......
  • springboot优点
    传统的Spring应用部署时,通常会将应用打成WAR包形式并部署到Tomcat、Jetty或Undertow服务器中。 SpringBoot框架内嵌了Tomcat、Jetty和Undertow服务器,于是可以将应用打包成jar,直接运行一个jar包就能启动一个web服务 是怎么内嵌的tomcat 这个依赖是SpringBootStar......
  • DC-DC电源模块直流隔离升压变换器高压稳压输出50V/110V/130V/150V/220V/250V/300V/500
    HRB系列隔离宽电压输入高电压稳压输出特点●效率高达 80%以上●1*2英寸标准封装●单电压输出●价格低●稳压输出●工作温度:-40℃~+85℃●阻燃封装,满足UL94-V0要求●温度特性好●可直接焊在PCB上应用HRBW2~40W系列模块电源是一种DC-DC升压变换器。该模块电源的输入......
  • spring boot请求接口地址报404的几种情况
     1接口地址错误,这个不用解释了吧,就是地址搞错了2请求方法错误,如:get,你用了post3使用了springsecurity,没有开放这个接口,导致请求不到4在application.yml的配置文件里为servlet添加了context-path配置,如:server:port:8129servlet:context-path:/share这个......
  • 如何在Spring Boot中使用Hibernate Natural ID
    首先,让我们关注所需类的实现。完成所有这些后,我们将能够为具有自然ID的实体提供存储库。用自然ID编写实体让我们考虑以下具有自动生成ID和自然ID(code列)的实体。这只是一个使用一个自然ID的典型实体@NaturalId:@实体publicclassProductimplementsSerializable{priva......
  • 从 SpringApplication 认识 Spring 应用启动过程
    一、SpringApplication是什么?Spring应用的启动类。二、SpringApplication执行了什么?创建ApplicationContext实例ApplicationContext就是我们所说的容器实例。注册CommandLinePropertySourceCommandLinePropertySource的作用是将命令行参数输出为Spring属性。......
  • 解惑 spring 嵌套事务
    解惑spring嵌套事务/***@author王政*@date2006-11-24*/在所有使用spring的应用中,声明式事务管理可能是使用率最高的功能了,但是,从我观察到的情况看,绝大多数人并不能深刻理解事务声明中不同事务传播属性配置的的含义,让我们来看一下Trans......
  • 淘宝接口数据采集获得店铺详情api接口获取源代码调用示例展示
     淘宝店铺详情API接口是阿里巴巴开放平台提供的一种API接口,用于获取指定淘宝店铺的详细信息,如店铺名称、店铺简介、开店时间、主营类目等信息。具体来说,淘宝店铺详情API接口(免费获取调用私信)的作用包括:1.获取店铺基本信息:可以获取店铺名称、描述、卖家主页、好评率等基本信息,帮助......