Back to Javatutorial

Springע

docs/Spring全家桶/Spring/Spring常见注解.md

1.0.013.0 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

ο

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