Back to Javatutorial

Springע

docs/Spring全家桶/SpringBoot/Spring常见注解使用指南(包含Spring+SpringMVC+SpringBoot).md

1.0.019.8 KB
Original Source

Springע

1

Ƕ֪SpringĵԾIOC+AOPIOCԭʵһSpringSpring Beanʵ DIҲע룬ΪҪĵĺĻ⣬עעĸҪȷ֪ġ ǰϰxmlļһbeanڣǸʹעʹDIĹ

ǿʹ org.springframework.beans.factory.annotation org.springframework.context.annotation еע Spring DI Ĺܡ

ͨЩΪSpring ע͡ǽڱ̳жлعˡ

2 DIע

2.1 @Autowired

ǿʹ @Autowired Spring Ҫע ǿԽע빹캯setter ֶעһʹá Constructor injection:

ע

class Car {
    Engine engine;

    @Autowired
    Car(Engine engine) {
        this.engine = engine;
    }
}

Setterע

class Car {
    Engine engine;

    @Autowired
    void setEngine(Engine engine) {
        this.engine = engine;
    }
}

ע

class Car {
    @Autowired
    Engine engine;
}

@Autowired һΪ required IJĬֵΪ true

Ҳʵ bean ʱ Spring Ϊ Ϊ true ʱ׳쳣κݡ

ע⣬ʹù캯ע룬й캯ǿԵġ

4.3 汾ʼDzҪʽʹ @Autowired ע⹹캯캯

2.2 @Bean

@Bean ʵ Spring bean Ĺ

@Bean
Engine engine() {
    return new Engine();
}

Ҫ͵ʵʱSpring Щ

ɵ bean 빤ͬ Բͬķʽǿʹôע͵ƻֵֵDzƵı

@Bean("engine")
Engine getEngine() {
    return new Engine();
}

һַdzbeanʽΪܶbeanһʼڴﶨõģҪʱа蹹

ǿɵͶBeanҲԸԶbeanơ

ע⣬@Bean ע͵ķ@Configuration С

2.3 @Qualifier

ʹ@Qualifier @Autowired ṩҪڲȷʹõbean id bean ơ

磬 bean ʵͬĽӿڣ

class Bike implements Vehicle {}

class Car implements Vehicle {}

Spring Ҫעһ Vehicle beanԶƥ䶨 £ǿʹ @Qualifier עʽṩ bean ơ

ע

@Autowired
Biker(@Qualifier("bike") Vehicle vehicle) {
this.vehicle = vehicle;
}

Setterע

@Autowired
void setVehicle(@Qualifier("bike") Vehicle vehicle) {
this.vehicle = vehicle;
}

:

@Autowired
@Qualifier("bike")
void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;

ע

@Autowired
@Qualifier("bike")
Vehicle vehicle;

עǿƽõIJ࣬ǵһӿжʵʱͻᾭó

2.4 @Required

@Required setter ϱҪͨ XML 

@Required
void setColor(String color) {
this.color = color;
}

xml

<bean class="com.baeldung.annotations.Bike">
    <property name="color" value="green" />
</bean>

򣬽׳ BeanInitializationException dzټ÷֪һ¾

2.5 @Value

ǿʹ @Value ֵע bean 빹캯setter ֶעݡ

ҲǷdzõһע⣬ΪǺܶʱҪapplication.propertiesļȡֵ

ע

Engine(@Value("8") int cylinderCount) {
this.cylinderCount = cylinderCount;
}

setterע

@Autowired
void setCylinderCount(@Value("8") int cylinderCount) {
this.cylinderCount = cylinderCount;
}

:


@Value("8")
void setCylinderCount(int cylinderCount) {
this.cylinderCount = cylinderCount;
}

ע

@Value("8")
int cylinderCount;

Ȼע뾲ֵ̬ûõġ ˣǿ @Value ʹռλַⲿԴжֵ .properties .yaml ļС


engine.fuelType=petrol

ǿͨ·ʽע engine.fuelType ֵ

@Value("${engine.fuelType}")
String fuelType;

ʹ SpEL ʹ@Value ߼ʾǹ@Value ҵ

2.6 @DependsOn

ǿʹôע Spring ע bean ֮ǰʼ bean ͨΪԶģ bean ֮ʽϵ

ֻʽʱҪע⣬JDBCػ߾̬ʼ

ǿָ bean Ƶʹ @DependsOn ע͵ֵҪһ bean Ƶ飺

@DependsOn("engine")
class Car implements Vehicle {}

Alternatively, if we define a bean with the @Bean annotation, the factory method should be annotated with @DependsOn:

@Bean
@DependsOn("fuel")
Engine engine() {
return new Engine();
}

2.7 @Lazy

سʼǵ bean ʱʹ @Lazy Ĭ£Spring Ӧóĵ/ʱеشе bean

ǣЩҪʱ beanӦóʱ

עΪǷȷλöͬ ǿ԰ڣ

һ @Bean ע͵ bean ӳٷã˴ bean @Configuration а@Bean ܵӰ

һ @Component ࣬ @Configuration ࣬ bean ӳٳʼ

@Autowired 캯setter ֶΣӳټͨ

@Configuration
@Lazy
class VehicleFactoryConfig {

    @Bean
    @Lazy(false)
    Engine engine() {
        return new Engine();
    }
}

ͬһõע⡣

άһдbeanĿʱᷢкܶbeanܶǰʹõģһҪʼʱͽгʼ԰ǽʡܶʱܡ

2.8 @Lookup

ͬһȽõע

@Lookup Spring ǵʱط͵ʵ

ϣSpring Ǵע͵ķʹǷķͺͲΪ BeanFactory#getBean IJ

@Lookup ڣ

ԭ bean עԼbean Provider

ɾӵһԭ Spring beanôǼ⣺

ǵĵ Spring bean ηЩԭ Spring bean

ڣProvider ϶һַʽ @Lookup ijЩͨá

ҪעǣspringĬʹõĵbeanҪעԭbeanDzҪĶ⹤

ȣǴһԭ beanԺǽע뵽 bean У

@Component
@Scope("prototype")
public class SchoolNotification {
// ... prototype-scoped state
}

ʹ@Lookupǿͨ bean ȡ SchoolNotification ʵ

@Component
public class StudentServices {

    // ... member variables, etc.

    @Lookup
    public SchoolNotification getNotification() {
        return null;
    }

    // ... getters and setters
}

Using @Lookup, we can get an instance of SchoolNotification through our singleton bean:

@Test
public void whenLookupMethodCalled_thenNewInstanceReturned() {
// ... initialize context
StudentServices first = this.context.getBean(StudentServices.class);
StudentServices second = this.context.getBean(StudentServices.class);

    assertEquals(first, second); 
    assertNotEquals(first.getNotification(), second.getNotification()); 
}

ע⣬ StudentServices Уǽ getNotification Ϊ

Ϊ Spring ͨ beanFactory.getBean(StudentNotification.class) ˸÷ǿԽա

2.9 @Primary

ʱҪͬ͵bean Щ£ע뽫ɹΪ Spring ֪Ҫĸ bean

Ѿ˴ѡ@Qualifier нߵ㲢ָ bean ơ

ȻʱҪһض beanҪ bean

ǿʹ@Primary @Primary õbeanunqualifiedעϱѡ

@Component
@Primary
class Car implements Vehicle {}

@Component
class Bike implements Vehicle {}

@Component
class Driver {
@Autowired
Vehicle vehicle;
}

@Component
class Biker {
@Autowired
@Qualifier("bike")
Vehicle vehicle;
}

ǰʾУҪ ˣ Driver УSpring עһ Car bean Ȼ Biker bean Уֶ vehicle ֵһ Bike Ϊqualifiedġ

2.10 @Scope

ͨӦ˵beanscopeĬ϶ǵģʵspring beanֶֶ֧÷ΧŲͬڡ

ʹ@Scope @Component @Bean ķΧ ǵԭ͡󡢻ỰglobalSession һЩԶ巶Χ

ӦöֵΪ

singleton
prototype
request
session
application
websocket
@Component
@Scope("prototype")
class Engine {}

ǿһЩrequestsessionwebsocketbeanͨӦǺصģô洢ûϢsession֮bean

ôʹãҪľ峡ѡˣһܴĻ⣬ȲչˣԺڵܡ

3 ע

ǿʹñעӦóġ

3.1 @Profile

ϣ Spring ضļڻ״̬ʱʹ@Component @Bean ǿʹ@Profile бǡ

ǿʹע͵ֵļƣ

ͨעòͬá

public interface DatasourceConfig {
public void setup();
}

ǿã

@Component
@Profile("dev")
public class DevDatasourceConfig implements DatasourceConfig {
@Override
public void setup() {
System.out.println("Setting up datasource for DEV environment. ");
}
}

ã

@Component
@Profile("production")
public class ProductionDatasourceConfig implements DatasourceConfig {
@Override
public void setup() {
System.out.println("Setting up datasource for PRODUCTION environment. ");
}
}

ȻҲʹxml͵ļbean

xml

<beans profile="local">
    <bean id="localDatasourceConfig" 
      class="org.test.profiles.LocalDatasourceConfig" />
</beans>

3.2 @Import

ǿʹض @Configuration ࣬ʹôעɨ衣 ǿΪЩṩ@Import ֵ

˵Ҫõ@ConfigurationעbeanôspringӦñҪɨ赽Ŀ¼ǡûжԸ·ɨ裬ֻʹ·µĵ࣬ôǾͿʹ@Importˡ

ע⻹Ƿdzõģһ

@Import(VehiclePartSupplier.class)
class VehicleFactoryConfig {}

@Configuration
class VehiclePartSupplier{
}

3.3 @ImportResource

˵һ bean.xml ļҪ beans.xml ж bean 뵽 Spring Boot Уβأ

1.Spring ʽļ bean.xml ˴ٸʾ˵ xml һ helloServiceʾ

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- HelloService xmlķʽ,ע뵽-->
    <bean id="helloService" class="com.demo.springboot.service.HelloService"></bean>
</beans>

2.ʹ@ImportResourceע⣬ xml

/**
 * Spring BootûSpringļԼдļҲԶʶ
 * SpringļЧصSpring 
 * ʹ@ImportResourceע⣬עһ(˴)
 */
@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class BootApplication {

    public static void main(String[] args) {
        // SpringӦ         
        SpringApplication.run(BootApplication.class,args);

    }
}

3.4 @PropertySource

ͨע⣬ǿΪӦóöļ

@PropertySource עṩһַԻƣڽ PropertySource ӵ Spring Environment У @Configuration һʹá

ʹ @Value ȥöԣ磺@Value("testbean.name")ҲָĬֵ磺@Value("testbean.name:defaultValue")

÷ʾ

һļapp.properties

testbean.name=myTestBean

@Configuration ʹ @PropertySource app.properties ø Environment PropertySources ϡ

@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {

    @Autowired
    Environment env;
 
    @Bean
    public TestBean testBean() {
        TestBean testBean = new TestBean();
        testBean.setName(env.getProperty("testbean.name"));
        return testBean;
    }
}

ע⣺ʹ @Autowired Environment ע뵽УȻ testBean() ʹá У testBean.getName() ءmyTestBeanַ

@PropertySource Java 8 ظעԣζǿαһࣺ

@Configuration
@PropertySource("classpath:/annotations.properties")
@PropertySource("classpath:/vehicle-factory.properties")
class VehicleFactoryConfig {}

3.5 @PropertySources

÷ͬϣֻһǿʹעָ@PropertySource ã

@Configuration
@PropertySources({
@PropertySource("classpath:/annotations.properties"),
@PropertySource("classpath:/vehicle-factory.properties")
})
class VehicleFactoryConfig {}

ע⣬ Java 8 ǿͨظע͹ʵͬĹܡ

4.

ڱУǿ Spring ע͵ĸ ǿ bean ӺӦģԼΪɨࡣ

springϵеijע⻹кܶ࣬һƪ²ȫǣ©ӭ䡣

Spring Beanע

1

ڱ̳Уǽڶ岻ͬ bean  Spring bean ע͡

мַ Spring bean ȣǿʹ XML ǡ ǻʹ@Bean ע bean

ǿʹ org.springframework.stereotype еע֮һǸ࣬ಿɨ衣

2 @ComponentScan

Ǿʹõһע⣬ǵӦУʱһɨеİرǵҪɨⲿjarеbeanʱdzá

ԼSpringBootApplicationϣҲԼ@configurationעϵ

ɨ裬Spring Զɨе bean

@ComponentScan ʹעɨЩࡣ

ǿֱʹ basePackages value ֮һָƣvalue basePackages ı

@Configuration
@ComponentScan(basePackages = "com.baeldung.annotations")
class VehicleFactoryConfig {}

⣬ǿʹ basePackageClasses ָеࣺ

@Configuration
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
class VehicleFactoryConfig {}

飬ǿΪÿṩ

δָɨ跢ڴ @ComponentScan עͬһС

@ComponentScan Java 8 ظעԣζǿαһࣺ

@Configuration
@ComponentScan(basePackages = "com.baeldung.annotations")
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
class VehicleFactoryConfig {}

ߣǿʹ @ComponentScans ָ @ComponentScan ã

@Configuration
@ComponentScans({
@ComponentScan(basePackages = "com.baeldung.annotations"),
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
})
class VehicleFactoryConfig {
}

ʹ XML ʱɨͬ򵥣

<context:component-scan base-package="com.baeldung"/>

3 @Component

@Component ༶ע⡣ ɨڼ䣬Spring Framework Զʹ@Component עࣺ

@Component
class CarUtility {
// ...
}

Ĭ£ bean ʵͬĸСд ⣬ǿʹôע͵Ŀѡֵָͬơ

@Repository@Service@Configuration @Controller Ǵ@Component ע⣬ǹͬbean Ϊ

Spring ɨԶǡ

ͨ˵ǻmvcӦǻõע⣬ڷwebӦиؿʹ@componentעbean

4 @Repository

DAO or Repository classes usually represent the database access layer in an application, and should be annotated with @Repository:

@Repository
class VehicleRepository {
// ...
}

ʹôע͵һŵԶ־쳣ת ʹó־Կܣ Hibernateʱʹ @Repository ע͵׳ı쳣ԶתΪ Spring DataAccessExeption ࡣ

Ҫ쳣תҪԼ PersistenceExceptionTranslationPostProcessor bean

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}

ע⣬ڴ£Spring Զִ衣

ͨ XML ã

<bean class=
"org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

5 @Service

Ӧóҵ߼ͨפڷУǽʹ@Service עָʾһڸò㣺

@Service
public class VehicleService {
// ...    
}

6 @Controller

@Controller һ༶ע⣬ Spring Framework Ϊ Spring MVC еĿ

spring@Controller עbeanܶ飬ǻSpringMVCص

@Controller
public class VehicleController {
// ...
}

7 @Configuration

԰@Bean ע͵ bean 巽

@Configuration
class VehicleFactoryConfig {

    @Bean
    Engine engine() {
        return new Engine();
    }

}

8 AOPע

ʹ Spring עʱ״һ㣬оض͵ΪĿꡣ

磬 DAO 㷽ִʱ䡣 ǽ·棨ʹ AspectJ עͣ @Repository ͣ

@Aspect
@Component
public class PerformanceAspect {
@Pointcut("within(@org.springframework.stereotype.Repository *)")
public void repositoryClassMethods() {};

    @Around("repositoryClassMethods()")
    public Object measureMethodExecutionTime(ProceedingJoinPoint joinPoint) 
      throws Throwable {
        long start = System.nanoTime();
        Object returnValue = joinPoint.proceed();
        long end = System.nanoTime();
        String methodName = joinPoint.getSignature().getName();
        System.out.println(
          "Execution of " + methodName + " took " + 
          TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
        return returnValue;
    }
}

ڴʾУǴһ㣬ƥʹ@Repository ע͵ез Ȼʹ@Around ֪ͨλǸ㣬ȷطõִʱ䡣

⣬ʹַǿΪÿӦó־¼ܹƺΪ

ȻˣaspectJע⻹ܶ࣬棬δҲᵥдĽܡ

9

ڱУǼ Spring עͲǸԴ͡

ǻѧϰʹɨҵע͵ࡣ

˽Щעε¸ɾֲԼӦóע֮ķ롣 ǻʹøСΪDzҪֶʽ bean

SpringMVCע

1.

ڱ̳Уǽ̽ org.springframework.web.bind.annotation е Spring Web ע͡

2. @RequestMapping

򵥵˵@RequestMapping @Controller ڲ򷽷 ʹã

·ƺֵӳ䵽ĸ URL ݵ HTTP params HTTP Ĵڡڻֵ headers HTTP ͷĴڡڻֵ ģ÷ HTTP Щý produces÷ HTTP ӦЩý һ򵥵ʾ

@Controller
class VehicleController {

    @RequestMapping(value = "/vehicles/home", method = RequestMethod.GET)
    String home() {
        return "home";
    }
}

༶ӦôעͣǿΪ @Controller ед򷽷ṩĬá Ψһ Spring ʹ÷øǵḽ·ֵ URL

磬úЧһģ

@Controller
@RequestMapping(value = "/vehicles", method = RequestMethod.GET)
class VehicleController {

    @RequestMapping("/home")
    String home() {
        return "home";
    }
}

⣬@GetMapping@PostMapping@PutMapping@DeleteMapping @PatchMapping @RequestMapping IJͬ壬HTTP ѷֱΪGETPOSTPUTDELETE PATCH

Щ Spring 4.3 汾ʼá

3 @RequestBody

Ǽ@RequestBody HTTP ӳ䵽һ

@PostMapping("/save")
void saveVehicle(@RequestBody Vehicle vehicle) {
// ...
}

лԶģȡ͡

4 @PathVariable

˵˵@PathVariable

עָʾ󶨵 URI ģ ǿʹ @RequestMapping עָ URI ģ壬ʹ @PathVariable 󶨵ģ岿֮һ

ǿʹƻֵʵһ㣺

@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable("id") long id) {
// ...
}

ģвֵ뷽ƥ䣬ǾͲעָ

@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable long id) {
// ...
}

⣬ǿͨIJΪ false ·Ϊѡ

@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable(required = false) long id) {
// ...
}

5. @RequestParam

We use @RequestParam for accessing HTTP request parameters:

@RequestMapping
Vehicle getVehicleByParam(@RequestParam("id") long id) {
// ...
}

@PathVariable עͬѡ

Щ֮⣬ Spring зûֵΪֵʱǿʹ @RequestParam ָעֵ ΪˣDZ defaultValue

ṩĬֵʽ required Ϊ false

@RequestMapping("/buy")
Car buyCar(@RequestParam(defaultValue = "5") int seatCount) {
// ...
}

˲֮⣬ǻԷ HTTP 󲿷֣cookie ͱͷ

ǿԷֱʹע@CookieValue @RequestHeader ǡ

6. Response Handling Annotations

ڽIJУǽ Spring MVC в HTTP Ӧע͡

6.1 @ResponseBody

@ResponseBody 򷽷Spring ὫĽΪӦ

@ResponseBody
@RequestMapping("/hello")
String hello() {
return "Hello World!";
}

עע @Controller ࣬򷽷ʹ

6.2 @ExceptionHandler

ʹôעͣǿһԶ򷽷 򷽷׳κָ쳣ʱSpring ô˷

쳣Ϊݸ

@ExceptionHandler(IllegalArgumentException.class)
void onIllegalArgumentException(IllegalArgumentException exception) {
// ...
}

6.3 @ResponseStatus

ʹôעͶ򷽷עָͣӦ HTTP ״̬ ǿʹ code value ״̬롣

⣬ǿʹ reason ṩԭ

ҲԽ@ExceptionHandler һʹã

@ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) void onIllegalArgumentException(IllegalArgumentException exception) { // ... }

й HTTP Ӧ״̬ĸϢʱġ

7 Webע

һЩעͲֱӹ HTTP Ӧ ڽIJУǽġ

7.1 @Controller

ǿʹ@Controller һSpring MVC йظϢǹ Spring Bean Annotations ¡

7.2 @RestController

@RestController @Controller @ResponseBody

ˣǵЧģ

@Controller
@ResponseBody
class VehicleRestController {
// ...
}
@RestController
class VehicleRestController {
// ...
}

7.3 @ModelAttribute

ͨע⣬ǿͨṩģͼѾ MVC @Controller ģеԪأ

@PostMapping("/assemble")
void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicleInModel) {
// ...
}

@PathVariable @RequestParam һͬƣDzָģͼ

@PostMapping("/assemble")
void assembleVehicle(@ModelAttribute Vehicle vehicle) {
// ...
}

⣬@ModelAttributeһ;עһSpringԶķֵӵģУ

@ModelAttribute("vehicle")
Vehicle getVehicle() {
// ...
}

ǰһDzָģͼSpring Ĭʹ÷ƣ

@ModelAttribute
Vehicle vehicle() {
// ...
}

Spring 򷽷֮ǰ @ModelAttribute ע͵ķ

й @ModelAttribute ĸϢıġ

7.4 @CrossOrigin

@CrossOrigin Ϊע͵򷽷ÿͨţ

@CrossOrigin
@RequestMapping("/hello")
String hello() {
return "Hello World!";
}

һ࣬е򷽷

ǿʹôע͵IJ΢ CORS Ϊ

йϸϢʱġ

SpringBootע

1

Spring Boot ͨԶùʹ Spring øס

ڱٽ̳Уǽ̽ org.springframework.boot.autoconfigure org.springframework.boot.autoconfigure.condition еע⡣

2 @SpringBootApplication

ʹע Spring Boot Ӧóࣺ

@SpringBootApplication ʹע Spring Boot Ӧóࣺ

@SpringBootApplication
class VehicleFactoryApplication {

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

@SpringBootApplication װ@Configuration@EnableAutoConfiguration @ComponentScan ע⼰Ĭԡ

3 @EnableAutoConfiguration

@EnableAutoConfiguration˼壬Զá ζ Spring Boot ·вԶ bean ԶӦǡ

ע⣬DZ뽫ע@Configuration һʹã

@Configuration
@EnableAutoConfiguration
class VehicleFactoryConfig {}

4 @ConfigurationԼ

@Configurationãעϣspring(Ӧ)

springbeanʹõxmlļһbeanspringbootУΪãspringṩ@Configurationһע

൱ڰѸΪspringxmlļе<beans>

@ConfigurationעУʹ@BeanעעķصͶֱעΪbean

@ConfigureעĶ£

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
String value() default "";
}

ӶײǺ@Component @Configuration к @Component ácontext:component-scan/@ComponentScanܴ@Configurationעࡣ

ͨDZдԶԶʱϣ Spring ʹǡ ǿͨеעʵһ㡣

ǿԽ˲еעͷ@Configuration @Bean ϡ

ڽIJУǽֻÿĻ ˽Ϣƪ¡

4.1 @ConditionalOnClass and @ConditionalOnMissingClass

һжϵע⣬Ҫ֪ܶʱǰbeanģǸⲿjarǷмغжϵġ

ʱ򣬾ҪⲿǷǷǷظbean

ʹЩעͲе/ڣSpring ʹñǵԶ bean

@Configuration
@ConditionalOnClass(DataSource.class)
class MySQLAutoconfiguration {
//...
}

4.2 @ConditionalOnBean and @ConditionalOnMissingBean

Ҫض bean Ĵڻ򲻴ʱǿʹЩעͣ

һעЩͬΪǵжbean

@Bean
@ConditionalOnBean(name = "dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// ...
}

4.3 @ConditionalOnProperty

ͨע⣬ǿԶԵֵ

Ҫע⣬ֵԴapplication.propertiesļе

@Bean
@ConditionalOnProperty(
name = "usemysql",
havingValue = "local"
)
DataSource dataSource() {
// ...
}

4.4 @ConditionalOnResource

ǿ Spring ڴضԴʱʹö壺 ˼壬ҪclasspathԴļʱŽмأҲǺܳõһע⡣


@ConditionalOnResource(resources = "classpath:mysql.properties")
Properties  ditionalProperties() {
// ...
}

4.5 @ConditionalOnWebApplication and @ConditionalOnNotWebApplication

עͨںwebǿȫ޹

ʹЩעͣǿԸݵǰӦóǷ Web Ӧó


@ConditionalOnWebApplication
HealthCheckController healthCheckController() {
// ...
}

4.6 @ConditionalExpression

springbootΪ뵽ע⻹ҪôɴԼдӦûɣ

ǿڸӵʹע⡣ SpEL ʽΪʱSpring ʹñǵĶ壺

@Bean
@ConditionalOnExpression("${usemysql} && ${mysqlserver == 'local'}")
DataSource dataSource() {
// ...
}

4.7 @Conditional

ʲô⣿ springbootҲṩʲôʽˣֱûдһжtruefalse

ڸӵǿԴһԶࡣ Ǹ Spring Զ @Conditional һʹã

@Conditional(HibernateCondition.class)
Properties  ditionalProperties() {
//...
}

5 ܽ

ڱУǸ΢Զù̲ΪԶԶ bean ṩ

ο

https://www.baeldung.com/spring-annotations