springcloud 复习day1~[自动装配]
package com.gavin.eureka_server;public class First {private String auto="自动装配";public String getAuto() {return auto;}public void setAuto(String auto) {this.auto = auto;}
}
package com.gavin.eureka_server;public class Second {
}
装配:实现ImportSelector类
package com.gavin.eureka_server;import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;public class GpImportSelector implements ImportSelector {
//返回要注入的bean名~@Overridepublic String[] selectImports(AnnotationMetadata importingClassMetadata) {return new String[]{First.class.getName(),Second.class.getName()};}
}
自定义注解:
package com.gavin.eureka_server;import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.context.annotation.Import;import java.lang.annotation.*;@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(GpImportSelector.class)
public @interface EnableAutoImport {
}
启动类:
package com.gavin.eureka_server;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.ConfigurableApplicationContext;@EnableEurekaServer
@SpringBootApplication
@EnableAutoImport
public class EurekaServerApplication {public static void main(String[] args) {ConfigurableApplicationContext run = SpringApplication.run(EurekaServerApplication.class, args);//可以取到要装配的类First bean = run.getBean(First.class);System.out.println(bean.getAuto());}}