【问题标题】:春季如何注入pojo类?
【发布时间】:2022-01-23 16:31:21
【问题描述】:

我有一个 pojo 类,我需要在组件中注入它。如何在春天注入 pojo 对象? 例如 RestClass 在 Module 下(就像一个微服务)。 Pojo 值应仅在此处注入。服务类和 pojo 是不同的模块。

@Controller
public class RestClass {

 @Autowired
 private ServiceClass serviceClass;
 // How to apply MyConfig pojo object into ServiceClass
 //like MyConfig.Builder().limit(100).build();
 @PostMapping("/business")
 private void callDoBusiness(){
   serviceClass.doBusiness();
 }

}
//// ServiceClass and Pojo class is under one module. Pojo object should not construct here. should be passed from another module

@Service
public class ServiceClass {

 @Autowired
 private MyConfig myConfig;

 public void doBusiness(){
    System.out.println(myConfig.getLimit())
 }

}


@Builder
@Getter
public class MyConfig {

 private int limit;
 .
 .

}

【问题讨论】:

  • 作为最简单的方法,您是否考虑过在Config-annotated 配置中创建一个返回MyConfig 实例的Bean-annotated 方法?
  • @Bean 的值将如何设置? ServiceClass 和 Pojo 类在一个模块中。控制器是其他模块吗?在哪里创建@Configuration。你能帮忙吗?
  • 模块没有任何作用。再说一遍:赞成的答案是建议您这样做。请注意,您还可以将 @Value-annotated 参数注入该方法。到目前为止,我看不到真正的问题。

标签: java spring rest


【解决方案1】:

你可以使用@Bean

@Configuration
  public class Config {
  @Bean
  public MyConfig MyConfig() {
    return new MyConfig();
  }
}

【讨论】:

    【解决方案2】:

    您可以使用@Configuration 和@Bean。像这样的

    AppConfig.java

    @Configuration
    public class AppConfig {
    
        @Bean
        public PojoClass getBean(){ return new PojoClass();}
    
    }
    

    【讨论】:

    • 我已经编辑了我的问题。请考虑
    • @shree 只需添加具有 (pojo) 的模块对模块(你需要 pojo 的地方)的依赖。
    【解决方案3】:

    @Bean 注释用于您的情况。例如:

    使用@Configuration 注释创建一些配置文件。在哪里创建 Config 配置类或如何命名它并不重要。您甚至可以在整个项目中拥有多个 @Configuration 类。

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    
    class Config {
      // configure your MyConfig class here as a bean
      @Bean
      public MyConfig myConfig() {
        return MyConfig.Builder().limit(100).build();
      }
    }
    

    现在你可以在任何你使用它的地方自动装配它,就像你的例子一样。

    【讨论】:

    • 我已经编辑了我的问题。请考虑...实际上 pojo 对象应该从控制器传递
    • @shree 如果您的控制器中需要 pojo,则只需将其自动连接到您的 RestClass 中,例如 @Autowire MyConfig myConfig
    • 那么如果我从控制器自动连线,该值将如何设置
    • 这是 Spring 完成的,所以你不必关心。
    • 无论何时自动连接MyConfig,您都会得到MyConfig.Builder().limit(100).build()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 2014-03-27
    • 2020-03-16
    相关资源
    最近更新 更多