【问题标题】:How to implement custom @Enable annotation?如何实现自定义@Enable注解?
【发布时间】:2020-11-24 22:02:36
【问题描述】:

我创建了注释@EnableMyConfiguration

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MyConfiguration.class)
public @interface EnableMyConfiguration{
}

并创建了简单的配置

@Configuration
@Slf4j
public class MyConfiguration {
    @Bean
    public String testStringBean() {
        String s = "Hello world";
        log.info("TeST LOG = {}", s);
        return s;
    }
}

pom.xml 中此库的依赖项:

  • org.springframework.boot:spring-boot-starter:2.3.2.RELEASE

我尝试在我的测试项目中使用这个启动器 该项目具有以下依赖项:

  • org.springframework.boot:spring-boot-starter-parent:2.3.1.RELEASE
  • 对我的库的依赖

在主类中

@SpringBootApplication
@EnableMyConfiguration
public class MainTest{
    public static void main(String[] args) {
        SpringApplication.run(MainTest.class, args);
    }
}

但它不起作用。我的 bean 没有创建。请你帮助我好吗?我会失去什么?

【问题讨论】:

  • 我真的不明白你在做什么?是的,您获得了自定义注释,但是您将 Configuration 类导入其中?为什么?您不会将事物导入注释中,而是将注释放在要添加其他行为的事物上。什么豆子?没有注解为 bean 的方法不是 bean
  • 只需创建一个自定义注解(没有导入),然后用它注解一个您想要附加行为的方法,然后使用 Spring AOP 添加附加行为,例如medium.com/@ashrithgn/…

标签: spring spring-boot


【解决方案1】:

确保您的库应用程序启用了spring-boot-maven-plugin

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

如果您使用的是 gradle,请使用 gradle 等效项。

到目前为止,您在 java 端的所有内容都是正确的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    相关资源
    最近更新 更多