Using spring "BeanDefinitionRegistry" register my custom bean ("SFTP" - shown below). The custom bean has @value, @Autowired, @Bean annotation. The "@Bean("${service.name}_sftpTemplate")" annotation is not invoked during spring startup.


@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Slf4j
public class SFTP {

    @Value("${${service.name}.host}")
    String sftpHost;

    String serviceName;

    SFTP() {
        log.info("{} - sftp constructor" , System.getProperty("service.name"));
        this.serviceName = System.getProperty("service.name");
    }

    @Autowired
    @Qualifier("dbTemplate")
    String dbTemplate;

    @Bean("${service.name}_sftpTemplate")
    public String sftpConnectionAtBean(@Value("${service.name}") String serviceName) {
        log.info("{} - @Bean called", serviceName);
        return serviceName + "_sftpTemplate";
    }


    @PostConstruct
    public void init() {
        Assert.notNull(dbTemplate, "DB Template is null");
        Assert.notNull(sftpHost, "SFTP host is null");
        Assert.isTrue(sftpHost.equals(serviceName + "_localhost"), "@value value is not matchec");
        log.info("{} - sftp service initalized with host - {}", serviceName, sftpHost);
    }
}
    @ConditionalOnProperty(name = "sftp.db.store.enabled", havingValue = "true", matchIfMissing = false)
    class SFTPJdbcConfig {

        SFTPJdbcConfig() {
            log.info("Inside SFTPJdbcConfig");
        }

        @Bean("dbTemplate")
        public String dbTemplate() {
            return "dbTemplate";
        }
    }

The '@ Bean("${service.name}_sftpTemplate")' in SFTP.java & " @ Bean("dbTemplate")" in SFTPJdbcConfig.java is not initialized/called and this class is loaded via

    public static void registerBean(ApplicationContext context, String beanName, Class<?> beanClass) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) context.getAutowireCapableBeanFactory();
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(beanClass);
        registry.registerBeanDefinition(beanName, beanDefinition);
    }
     // Bean registration dynamically
           registerBean(context,service +"SFTP", SFTP.class);
           context.getBean(service +"SFTP",SFTP.class);

// Failed 
        log.info("@Bean Git-SFTP -{}",context.getBean("git_sftpTemplate", SFTP.class) );

For the source refer to GIT Link - https://github.com/tamilsmani/spring-load-test

Comment From: snicoll

There's so much going in your application. Sorry but we can't justify spending time trying to figure out what you're trying to do. The application starts in my IDE but fails when run with mvn spring-boot:run.

Registering what looks like auto-configuration the way you do is a non starter, you just can't do that. Configuration classes are missing @Configuration so they're running in lite mode. You'll need to review the documentation and fix those issues. For usage question, use StackOverflow.