Home > Software design >  MongoURI @value variable is getting nulled
MongoURI @value variable is getting nulled

Time:07-15

In my code below, mongoURI initially pulls the correct URI string from application.properties, and connects to the database successfully. However, once I make a call to getUserByAuth0ID, I'm getting a "java.net.UnknownHostException: null: Name or service not known" error and debug statements show that mongoURI is now set to null.

What's going on? Nowhere in my code do I touch the value of mongoURI. My previous version of the code has mongoURI hardcoded as a variable and it runs with no issues.

@Service
public class DBConnectService {
    private static MongoCollection<User> users;
    private static Logger logger = LogManager.getLogger(DBConnectService.class);

    @Value("${package.mongoURI}")
    private String mongoURI;
    
    /**     Opens a connection to mongodb for the length of the program operation        */
    @PostConstruct
    public void init() {
        logger.info("Connecting to MongoDB");
        try {
            System.out.println (mongoURI);  // URI prints out correctly here
            CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
            CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
            MongoClientSettings clientSettings = MongoClientSettings.builder()
                    .applyConnectionString(new ConnectionString(mongoURI))
                    .codecRegistry(codecRegistry)
                    .build();
            
            MongoClient mongoClient = MongoClients.create(clientSettings);
            MongoDatabase database = mongoClient.getDatabase("db");
            users = database.getCollection("users", User.class);
        } catch(Exception e) {
            logger.error("MongoDB connection failure:\n"   e);
        }
    }

    public User getUserByAuth0ID (String authID) {
        System.out.println (mongoURI);  // URI prints out here as null
        User user = getUser(authID, "auth0ID");
        if (user == null) {
            user = createUserAccount(authID);
        }
        return user;
    }

    public static User getUser (String info, String field) {
        User user = users.find(eq(field, info)).first();
        return user; 
    }

    public static User createUserAccount (String authID) {
        JsonObject newUserInfo = Auth0Service.getUserInfo(authID);
        
        if (newUserInfo.get("email_verified").getAsBoolean()) {
            
            User newUser = new User()
                    .setEmail(newUserInfo.get("email").getAsString())
                    .setName(newUserInfo.get("name").getAsString())
                    .setAuth0ID(authID);
            
            users.insertOne(newUser);
            
            return newUser;
        } else {
            logger.info ("Email NOT verified");
            
            return null;
        }
    }

Application.properties line:

#       --- MongoDB ---
package.mongoURI = mongodb srv://admin:secretURL/?retryWrites=true&w=majority

CodePudding user response:

Your @Value annotation has incorrect details of mongoURI.Either use @Value("${nornir.mongoURI}") or change to package.mongoURI inside application.properties.

Edit: It is more likely you are calling getUserByAuth0ID manually something like --

DBConnectService service = new DBConnectService();
service.getUserByAuth0ID();

Because if mongoURI is coming as null, it means, this method getUserByAuth0ID is not getting called via spring way, i.e. by autowiring DBConnectService & then accessing this method; but rather it is getting called manually i.e. by manually creating object of DBConnectService.

If this is case, then it is obvious that your normal java object don't know about @Value annotation & hence it is not setting any value.

@PostConstruct will always works as it will get executed at startup when bean is getting created & hence @Value is working properly there.

To fix this issue, make sure you have spring bean of DBConnectService & you are accessing getUserByAuth0ID via that bean.

Edit 2 : --

Basic pseudo about how to use this in your calling class :

@Autowired
DBConnectService service;


public void yourdbMethod(){
 service.getUserByAuth0ID();
}
  • Related