SpringBoot-常用注解

配置注解:

@Component、@Configuration、@Bean、@Import、@Resource、@Qualifier、@Mapper、@Service、@autowired、@Value、@bean、@entity、@Table、@Transient

参数注解:

@param、@requestparam、@requestbody

代码:

Car

package com.wange.anno;

public interface Car {
    public void print();
}
View Code

Bmw

package com.wange.anno;

import org.springframework.stereotype.Component;

@Component
public class Bmw implements Car{
    @Override
    public void print() {
        System.out.println("我是BMW");
    }
}
View Code

RangeRover

package com.wange.anno;

import org.springframework.stereotype.Component;

@Component
public class RangeRover implements Car{
    @Override
    public void print() {
        System.out.println("我是range rover");
    }
}
View Code

ConfigurationA

package com.wange.anno;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ConfigurationA {

    @Bean("rangerover")
    public Car getRangerover(){
        return new RangeRover();
    }
}
View Code

ConfigurationB

package com.wange.anno;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ConfigurationB {

    @Bean("bmw")
    public Car getBmw(){
        return new Bmw();
    }
}
View Code

Config

package com.wange.anno;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({ConfigurationA.class, ConfigurationB.class})
public class Config {

}
View Code

Test

package com.wange.anno;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ContextLoaderTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        Car bmw = (Car)context.getBean("bmw");
        bmw.print();

        RangeRover rangeRover = (RangeRover)context.getBean("rangerover");
        rangeRover.print();
    }
}
View Code

结果:

我是BMW

我是range rover

猜你喜欢

转载自www.cnblogs.com/wange/p/9763950.html