文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡(jiǎn)書
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工作時(shí)不要求任何特定的代碼布局米同,但是有一些最佳實(shí)踐是很有幫助的猫十。
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.
當(dāng)一個(gè)類沒有包含一個(gè)package
聲明時(shí),它當(dāng)做是在default package
中。通常情況下不建議使用default package
架谎,應(yīng)該避免使用它。當(dāng)Spring Boot應(yīng)用使用@ComponentScan
崭篡,@EntityScan
或@SpringBootApplication
它會(huì)引起一些特別的問題淮摔,因?yàn)镾pring Boot會(huì)讀取每個(gè)jar中的每個(gè)類。
We recommend that you follow Java’s recommended package naming conventions and use a reversed domain name (for example,
com.example.project
).
?
我們建議你遵循Java推薦的包命名規(guī)范移怯,使用一個(gè)反轉(zhuǎn)的域名(例如香璃,
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.
通常我們建議你將你的主應(yīng)用類放在其它類之上的根包中舟误。@EnableAutoConfiguration
注解經(jīng)常放在你的主類(main class)中葡秒,對(duì)于某些像它隱式的定義了一個(gè)基search package
,例如嵌溢,如果你正在寫一個(gè)JPA應(yīng)用眯牧,@EnableAutoConfiguration
注解的類所在的包將被用來搜索@Entity
項(xiàng)。
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.
根包的應(yīng)用也允許使用@ComponentScan
注解而不需要指定basePackage
特性赖草。如果你的主類是在根包中学少,你也可以使用@SpringBootApplication
注解。
Here is a typical layout:
下面是一個(gè)典型的布局:
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
文件會(huì)聲明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源調(diào)用SpringApplication.run()
方法扣囊,但我們通常建議你主要的源是一個(gè)@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.
?
網(wǎng)上已經(jīng)發(fā)布了許多使用XML配置來進(jìn)行Spring配置的例子绒疗。但要盡可能的嘗試使用等價(jià)的Java注解侵歇。搜索
enable*
注解是一個(gè)好的開端。
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
放到一個(gè)單獨(dú)的類中吓蘑『兄粒可以使用@Import
注解來導(dǎo)入額外的配置類∈啃蓿或者枷遂,你可以使用@ComponentScan
來自動(dòng)獲得所有的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.
如果你絕對(duì)的必須使用基于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自動(dòng)配置會(huì)基于你添加的jar依賴試圖自動(dòng)配置你的Spring應(yīng)用痪伦。例如,如果HSQLDB
在你的classpath中雹锣,并且你沒有手動(dòng)的配置任何數(shù)據(jù)庫連接beans网沾,我們將會(huì)在自動(dòng)配置一個(gè)內(nèi)存中的數(shù)據(jù)庫。
You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration
or @SpringBootApplication
annotations to one of your @Configuration
classes.
你需要通過添加@EnableAutoConfiguration
或@SpringBootApplication
注解到你的@Configuration
類中的一個(gè)來選擇性的加入自動(dòng)配置蕊爵。
You should only ever add one
@EnableAutoConfiguration
annotation. We generally recommend that you add it to your primary@Configuration
class.
?
你應(yīng)該僅添加一個(gè)
@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.
自動(dòng)配置是非入侵性的攒射,在任何時(shí)候你都可以開始定義你自己的配置來替換自動(dòng)配置的指定部分醋旦。例如,如果你要添加你自己的DataSource
bean会放,默認(rèn)嵌入的數(shù)據(jù)庫支持將會(huì)退出饲齐。
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.
如果你需要找出當(dāng)前正在應(yīng)用的自動(dòng)配置和為什么,你可以用--debug
開關(guān)來啟動(dòng)你的應(yīng)用咧最。這將會(huì)使核心日志的輸出級(jí)別變?yōu)閐ebug級(jí)別并輸出一個(gè)自動(dòng)配置報(bào)告到控制臺(tái)捂人。
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.
如果你發(fā)現(xiàn)正在應(yīng)用特定的你不想使用的自動(dòng)配置類,你可以使用@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.
如果這個(gè)類不在classpath中滥搭,你可以使用這個(gè)注解的excludeName
特性并指定全限定名來代替。最后咨察,你也可以通過spring.autoconfigure.exclude
屬性來排除论熙,從而控制自動(dòng)配置類的列表。
You can define exclusions both at the annotation level and using the property.
?
你也可以在注解級(jí)別或使用屬性來定義排除項(xiàng)摄狱。
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.
你可以自由的使用任何標(biāo)準(zhǔn)的Spring框架技術(shù)來定義你的beans和它們注入的依賴脓诡。為了簡(jiǎn)便,我們經(jīng)常使用@ComponentScan
來發(fā)現(xiàn)你的beans媒役,結(jié)合@Autowired
構(gòu)造函數(shù)注入也工作的很好祝谚。
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.
如果你根據(jù)上面的建議組織你代碼(將你的應(yīng)用類放在根包中),你可以添加@ComponentScan
注解而不需要任何參數(shù)酣衷。你所有的應(yīng)用組件(@Component
交惯,@Service
,@Repository
穿仪,@Controller
等等)將會(huì)作為Spring bean進(jìn)行自動(dòng)注冊(cè)席爽。
Here is an example @Service
Bean that uses constructor injection to obtain a required RiskAssessor
bean.
下面是一個(gè)@Service
Bean的例子,通過使用構(gòu)造函數(shù)注入來獲得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 asfinal
, indicating that it cannot be subsequently changed.
?
注意使用構(gòu)造函數(shù)注入允許
riskAssessor
字段標(biāo)記為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的開發(fā)者總是在它們的主類上加上@Configuration
紫谷,@EnableAutoConfiguration
和@ComponentScan
注解齐饮。由于這些注解頻繁的在一起使用(尤其是你遵循上面的最佳實(shí)踐時(shí)),Spring Boot提供了一個(gè)方便的@SpringBootApplication
注解來代替它們笤昨。
The @SpringBootApplication
annotation is equivalent to using @Configuration
, @EnableAutoConfiguration
and @ComponentScan
with their default attributes:
@SpringBootApplication
注解等價(jià)于使用@Configuration
祖驱,@EnableAutoConfiguration
和@ComponentScan
以及它們的默認(rèn)特性:
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
的特性。