Spring Boot 2.0.0参考手册_中英文对照_Part III_14-18

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

14. Structuring your code

Spring Boot does not require any specific code layout to work, however, there are some best practices that help.

Spring Boot工作时不要求任何特定的代码布局,但是有一些最佳实践是很有帮助的。

14.1 Using the “default” package

When a class doesn’t include a package declaration it is considered to be in the “default package”. The use of the “default package” is generally discouraged, and should be avoided. It can cause particular problems for Spring Boot applications that use @ComponentScan, @EntityScan or @SpringBootApplication annotations, since every class from every jar, will be read.

当一个类没有包含一个package声明时,它当做是在default package中。通常情况下不建议使用default package,应该避免使用它。当Spring Boot应用使用@ComponentScan@EntityScan@SpringBootApplication它会引起一些特别的问题,因为Spring Boot会读取每个jar中的每个类。

We recommend that you follow Java’s recommended package naming conventions and use a reversed domain name (for example, com.example.project).

 

我们建议你遵循Java推荐的包命名规范,使用一个反转的域名(例如,com.example.project)。

14.2 Locating the main application class

We generally recommend that you locate your main application class in a root package above other classes. The @EnableAutoConfiguration annotation is often placed on your main class, and it implicitly defines a base “search package” for certain items. For example, if you are writing a JPA application, the package of the @EnableAutoConfiguration annotated class will be used to search for @Entity items.

通常我们建议你将你的主应用类放在其它类之上的根包中。@EnableAutoConfiguration注解经常放在你的主类(main class)中,对于某些像它隐式的定义了一个基search package,例如,如果你正在写一个JPA应用,@EnableAutoConfiguration注解的类所在的包将被用来搜索@Entity项。

Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute. You can also use the @SpringBootApplication annotation if your main class is in the root package.

根包的应用也允许使用@ComponentScan注解而不需要指定basePackage特性。如果你的主类是在根包中,你也可以使用@SpringBootApplication注解。

Here is a typical layout:

下面是一个典型的布局:

com
 +- example
     +- myproject
         +- Application.java
         |
         +- domain
         |   +- Customer.java
         |   +- CustomerRepository.java
         |
         +- service
         |   +- CustomerService.java
         |
         +- web
             +- CustomerController.java

The Application.java file would declare the main method, along with the basic @Configuration.

Application.java文件会声明main方法和基本的@Configuration

package com.example.myproject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {

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

}

15. Configuration classes

Spring Boot favors Java-based configuration. Although it is possible to call SpringApplication.run() with an XML source, we generally recommend that your primary source is a @Configuration class. Usually the class that defines the main method is also a good candidate as the primary @Configuration.

Spring Boot支持基于Java的注解。尽管可以通过XML源调用SpringApplication.run()方法,但我们通常建议你主要的源是一个@Configuration类。

Many Spring configuration examples have been published on the Internet that use XML configuration. Always try to use the equivalent Java-based configuration if possible. Searching for enable* annotations can be a good starting point.

 

网上已经发布了许多使用XML配置来进行Spring配置的例子。但要尽可能的尝试使用等价的Java注解。搜索enable*注解是一个好的开端。

15.1 Importing additional configuration classes

You don’t need to put all your @Configuration into a single class. The @Import annotation can be used to import additional configuration classes. Alternatively, you can use @ComponentScan to automatically pick up all Spring components, including @Configuration classes.

你不必将所有的@Configuration放到一个单独的类中。可以使用@Import注解来导入额外的配置类。或者,你可以使用@ComponentScan来自动获得所有的Spring组件,包括@Configuration类。

15.2 Importing XML configuration

If you absolutely must use XML based configuration, we recommend that you still start with a @Configuration class. You can then use an additional @ImportResource annotation to load XML configuration files.

如果你绝对的必须使用基于XML的配置,我们推荐你仍然从@Configuration类开始。你可以使用额外的@ImportResource注解来加载XML配置文件。

16. Auto-configuration

Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you have not manually configured any database connection beans, then we will auto-configure an in-memory database.

Spring Boot自动配置会基于你添加的jar依赖试图自动配置你的Spring应用。例如,如果HSQLDB在你的classpath中,并且你没有手动的配置任何数据库连接beans,我们将会在自动配置一个内存中的数据库。

You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration or @SpringBootApplication annotations to one of your @Configuration classes.

你需要通过添加@EnableAutoConfiguration@SpringBootApplication注解到你的@Configuration类中的一个来选择性的加入自动配置。

You should only ever add one @EnableAutoConfiguration annotation. We generally recommend that you add it to your primary @Configuration class.

 

你应该仅添加一个@EnableAutoConfiguration注解。我们通常建议你将它添加到你主要的@Configuration类中。

16.1 Gradually replacing auto-configuration

Auto-configuration is noninvasive, at any point you can start to define your own configuration to replace specific parts of the auto-configuration. For example, if you add your own DataSource bean, the default embedded database support will back away.

自动配置是非入侵性的,在任何时候你都可以开始定义你自己的配置来替换自动配置的指定部分。例如,如果你要添加你自己的DataSource bean,默认嵌入的数据库支持将会退出。

If you need to find out what auto-configuration is currently being applied, and why, start your application with the --debug switch. This will enable debug logs for a selection of core loggers and log an auto-configuration report to the console.

如果你需要找出当前正在应用的自动配置和为什么,你可以用--debug开关来启动你的应用。这将会使核心日志的输出级别变为debug级别并输出一个自动配置报告到控制台。

16.2 Disabling specific auto-configuration

If you find that specific auto-configure classes are being applied that you don’t want, you can use the exclude attribute of @EnableAutoConfiguration to disable them.

如果你发现正在应用特定的你不想使用的自动配置类,你可以使用@EnableAutoConfiguration注解的exclude特性来禁用它们。

import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}

If the class is not on the classpath, you can use the excludeName attribute of the annotation and specify the fully qualified name instead. Finally, you can also control the list of auto-configuration classes to exclude via the spring.autoconfigure.exclude property.

如果这个类不在classpath中,你可以使用这个注解的excludeName特性并指定全限定名来代替。最后,你也可以通过spring.autoconfigure.exclude属性来排除,从而控制自动配置类的列表。

You can define exclusions both at the annotation level and using the property.

 

你也可以在注解级别或使用属性来定义排除项。

17. Spring Beans and dependency injection

You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies. For simplicity, we often find that using @ComponentScan to find your beans, in combination with @Autowired constructor injection works well.

你可以自由的使用任何标准的Spring框架技术来定义你的beans和它们注入的依赖。为了简便,我们经常使用@ComponentScan来发现你的beans,结合@Autowired构造函数注入也工作的很好。

If you structure your code as suggested above (locating your application class in a root package), you can add @ComponentScan without any arguments. All of your application components (@Component, @Service, @Repository, @Controller etc.) will be automatically registered as Spring Beans.

如果你根据上面的建议组织你代码(将你的应用类放在根包中),你可以添加@ComponentScan注解而不需要任何参数。你所有的应用组件(@Component@Service@Repository@Controller等等)将会作为Spring bean进行自动注册。

Here is an example @Service Bean that uses constructor injection to obtain a required RiskAssessor bean.

下面是一个@Service Bean的例子,通过使用构造函数注入来获得RiskAssessor bean。

package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseAccountService implements AccountService {

    private final RiskAssessor riskAssessor;

    @Autowired
    public DatabaseAccountService(RiskAssessor riskAssessor) {
        this.riskAssessor = riskAssessor;
    }

    // ...

}

Notice how using constructor injection allows the riskAssessor field to be marked as final, indicating that it cannot be subsequently changed.

 

注意使用构造函数注入允许riskAssessor字段标记为final,意味着它接下来不能被修改。

18. Using the @SpringBootApplication annotation

Many Spring Boot developers always have their main class annotated with @Configuration, @EnableAutoConfiguration and @ComponentScan. Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative.

许多Spring Boot的开发者总是在它们的主类上加上@Configuration@EnableAutoConfiguration@ComponentScan注解。由于这些注解频繁的在一起使用(尤其是你遵循上面的最佳实践时),Spring Boot提供了一个方便的@SpringBootApplication注解来代替它们。

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes:

@SpringBootApplication注解等价于使用@Configuration@EnableAutoConfiguration@ComponentScan以及它们的默认特性:

package com.example.myproject;

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

@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {

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

}

@SpringBootApplication also provides aliases to customize the attributes of @EnableAutoConfiguration and @ComponentScan.

 

@SpringBootApplication也提供了别名来定制@EnableAutoConfiguration@ComponentScan的特性。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容