Inject parameters to constructor through annotation in Spring

后端 未结 1 1885
暖寄归人
暖寄归人 2021-02-07 09:30

I am using Spring Boot annotation configuration. I have a class whose constructor accepts 2 parameters (string, another class).

Fruit.java



        
1条回答
  •  迷失自我
    2021-02-07 09:51

    Apple must be a spring-managed bean:

    @Component
    public class Apple{
    
    }
    

    Fruit as well:

    @Component
    public class Fruit {
    
        @Autowired
        public Fruit(
            @Value("iron Fruit") String FruitType,
            Apple apple
            ) {
                this.FruitType = FruitType;
                this.apple = apple;
            }
    }
    

    Note the usage of @Autowired and @Value annotations.

    Cook should have @Component too.

    Update

    Or you could use @Configuration and @Bean annotations:

    @Configuration 
    public class Config {
    
        @Bean(name = "redapple")
        public Apple redApple() {
            return new Apple();
        }
    
        @Bean(name = "greeapple")
        public Apple greenApple() {
            retturn new Apple();
        }
    
        @Bean(name = "appleCook")
        public Cook appleCook() {
            return new Cook("iron Fruit", redApple());
        }
        ...
    }
    

    0 讨论(0)
提交回复
热议问题