1

I have the following class

public class ConnectionPool {

@Autowired
private Properties props;

@Autowired
private Key internalKey;

public ConnectionPool{
   System.out.println(internalKey);
   System.out.println(props);
}
}

I am creating the ConnectionPool class as a bean in the following way in a class called ApplicationConfig.

@Bean
ConnectionPool returnConnectionPool(){
    ConnectionPool cPool = new ConnectionPool();
    return cPool;
}

In the ApplicationConfig class I also have

@Bean
Properties returnAppProperties()
{
   Properties props = new Properties();
   return props;
}

@Bean 
Key returnInternalKey()
{
  Key key = new Key();
  return key;
}

Why does

   System.out.println(internalKey);
   System.out.println(props);

print null when the Spring mvc app is starting? I thought Spring took care of all the bean instantiation and injection? What else do I have to do?

user3809938
  • 1,114
  • 3
  • 16
  • 35

1 Answers1

1

The problems is

@Bean
ConnectionPool returnConnectionPool(){
    ConnectionPool cPool = new ConnectionPool();
    return cPool;
}

You are not letting spring autowire the dependencies inside the ConnectionPool class as you are explicitly creating it using new construct.

To make it work I would suggest you to have a constructor which take both the dependencies and then change your returnConnectionPool method to look like this

@Bean
ConnectionPool returnConnectionPool(Properties properties, Key key){
    ConnectionPool cPool = new ConnectionPool(properties, key);
    return cPool;
}

(P.S. this is just one of the possible solution but spring has a lot of other magical ways to do the same stuff :) )

Sneh
  • 3,527
  • 2
  • 19
  • 37