• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

无信不立

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

【spring微服务】spring-boot的注解功能

一、spring-boot容器的注解释义

@configuration
任何一个标注了@configuration的Java类定义都是一个JavaConfig配置类。

@bean
任何一个标注了@bean的方法,其返回值将作为一个bean定义注册到spring的ioc容器,方法名将默认成为该bean定义的id。

@ComponentScan
@ComponentScan用于配合一些元信息Java annotation,比如@component和@repository等,将标注了这些元信息annotation的bean定义类批量采集到spring的ioc容器中。
我们可以通过basePackages等属性来细粒度地定制@ComponentScan自动扫描的范围,如果不指定,则默认spring框架实现会从声明@ComponentScan所在类的package进行扫描。

@PropertySource与@PropertySources
@PropertySource用于从某些地方加载*.properties文件内容,并将其中的属性加载到ioc容器中,便于填充一些bean定义属性的占位符。

@Import与@ImportResource
@Import负责引入JavaConfig形式定义的ioc容器配置,如果有一些遗留的配置或者遗留系统需要以xml的形式来配置(比如dubbo框架),我们依然可以通过@ImportResource将它们一起合并到当前JavaConfig配置的容器中。

二、@SpringBootApplication

之前用户使用的是3个注解注解他们的main类。分别是@Configuration,@EnableAutoConfiguration,@ComponentScan。由于这些注解一般都是一起使用,spring boot提供了一个统一的注解@SpringBootApplication。

@SpringBootApplication = (默认属性)@Configuration + @EnableAutoConfiguration + @ComponentScan。

@SpringBootApplication 
public class ApplicationMain { 
    public static void main(String[] args) { 
        SpringApplication.run(Application.class, args); 
    } 
}
View Code

分开解释@Configuration,@EnableAutoConfiguration,@ComponentScan。

1、@Configuration:提到@Configuration就要提到他的搭档@Bean。使用这两个注解就可以创建一个简单的spring配置类,可以用来替代相应的xml配置文件。

<beans> 
    <bean id = "car" class="com.test.Car"> 
        <property name="wheel" ref = "wheel"></property> 
    </bean> 
    <bean id = "wheel" class="com.test.Wheel"></bean> 
</beans> 
View Code

 相当于:

@Configuration 
public class Conf { 
    @Bean 
    public Car car() { 
        Car car = new Car(); 
        car.setWheel(wheel()); 
        return car; 
    } 
    @Bean  
    public Wheel wheel() { 
        return new Wheel(); 
    } 
}
View Code

@Configuration的注解类标识这个类可以使用Spring IoC容器作为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean。

2、@EnableAutoConfiguration:能够自动配置spring的上下文,试图猜测和配置你想要的bean类,通常会自动根据你的类路径和你的bean定义自动配置。

3、@ComponentScan:会自动扫描指定包下的全部标有@Component的类,并注册成bean,当然包括@Component下的子注解@Service,@Repository,@Controller。

 

posted on 2019-09-11 20:54  无信不立  阅读(125)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3