SpringBoot入门实践(三)-工程结构及常用注解

  我的博客:兰陵笑笑生,欢迎浏览博客!

 上一章 SpringBoot入门实践(二)-配置文件及应用程序属性当中,我们介绍了SpringBoot的全局配置文件的讲解,实现了在配置文件中配置不同结构的数据,并且完成代码中如何获取到配置的值。本章将详细的讲解项目的工程结构和一些常用的注解。

项目的包名

 项目的主类(Application.class)一般都是在指定的包命下,例如:com.example.myapplicaiton. 采用反向命名法。我们不推荐没有包的主类.,这样会出现一些问题。

官方提供的典型布局

com
  - example
      - myapplication
          - Application.java
         |
          - customer
         |    - Customer.java
         |    - CustomerController.java
         |    - CustomerService.java
         |    - CustomerRepository.java
         |
          - order
              - Order.java
              - OrderController.java
              - OrderService.java
              - OrderRepository.java

主类

package com.example.myapplication;

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

@SpringBootApplication
public class Application {

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

}

 使用 @SpringBootApplication 注解 ,默认会扫描当前路径下的所有的使@Controller,@Service,@Component 等组件。

常用注解

1、注解 @SpringBootApplication:

​   @SpringBootApplication= @Configuration @EnableAutoConfiguration @ComponentScan

2、注解 @Configuration :

​   在spring时代,我们都是通过XML配置Bean的

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

 在spingBoot中

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

  使用@Configuration标识的类,可以认为当前的Conf就是一个XML,@Bean的类可以是Spring IOC中的bean的来源。

3、注解@EnableAutoConfiguration

  表面的含义就是开启自动配置,springBoot默认会加载一些开源的技术,约定大于配置的含义也是可以从这个注解中看到的。

 作用:将org.springframework.boot.autoconfigure.jar下的 类路径下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中,包括常用的数据库,elasticsearch、redis、security等大多数的应用。如下图

file

 具体是什么样的加载机制,请自行百度。

4、注解@ ComponentScan

 指定包路径,会扫描@Component@Service@Repository@Controller

 以上就是本期的分享,你还可以关注本博客的#Spring Boot入门实践系列!#

本文由博客一文多发平台 OpenWrite 发布!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值