0

Lets say i have properties class ExampleProps:

@ConfigurationProperties(prefix = "prefix.stuff")
@ConstructorBinding
@AllArgsConstructor
public class ExampleProps {
       ...
}

Which is located in src/main/java/com/example/props/. When spring scans for ConfigurationProperties it gives it following name

"prefix.stuff-com.example.props.ExampleProps"

Can i somehow change naming strategy to the regular one (Class name with lowercase first letter)?

Kravuar
  • 1
  • 1
  • For those interested how the bean name for @ConfigurationProperties is determined: https://github.com/spring-projects/spring-boot/blob/68fc87bc7fa74f5df34b814ebc157a65e263ca13/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java#L64-L67 – criztovyl Jul 23 '22 at 09:52

1 Answers1

0

You can control the name of the bean to which configuration properties are bound if you define it using a @Bean method:

@Configuration
class ExampleConfiguration {

    @Bean("theNameThatYouWantTheBeanToHave")
    @ConfigurationProperties("prefix.stuff")
    ExampleProps exampleProps {
        return new ExampleProps();
    }

}

For this to work, you'd have to stop using constructor binding and switch to setter-based binding instead. In outline form, that would leave ExampleProps looking like this:

public class ExampleProps {

   // Properties fields

   // Getters and setters

}

Having said this, I would think twice about following this approach. Generally speaking, the name that's assigned to a bean should not matter. You may want to look at why the name is important and see if that can be changed rather than trying to force the bean to have a particular name.

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • I think it would help understanding your answer to first explain how the name can be changed with an @Bean method, and then explain setter-based binding. I stopped reading two times because I though you were going into the wrong direction ^^ – criztovyl Jul 23 '22 at 09:51
  • 1
    @criztovyl I've reordered things a bit – Andy Wilkinson Jul 23 '22 at 10:12
  • "Generally speaking, the name that's assigned to a bean should not matter". @AndyWilkinson, what if I want utilize meta-data support and also utilize Spel, for example to setup `@KafkaListener` attribute? It means on one hand I need `@ConfigurationProperties` bean, on the other hand I need to know `@ConfigurationProperties` bean name – michaldo Mar 28 '23 at 09:44
  • @michaldo That's one reason why I said "generally speaking". There are some cases where knowing the name of the bean is important. Yours is one such case. – Andy Wilkinson Mar 28 '23 at 10:21