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

字数 2145阅读 154

文章作者: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的特性。

推荐阅读更多精彩内容