0

I have the following classes in the same package com.example.demo3.

@Component
public class Test {
    @Autowired
    Test2 test;
    public Test(){
        int i = 3;
    }
    public void print(){
        System.out.println(test);
    }
}
`package com.example.demo3;

import org.springframework.stereotype.Component;

@Component
public class Test2 {
    
}`

`package com.example.demo3;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.ServerApi;
import com.mongodb.ServerApiVersion;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

@Configuration
@SpringBootApplication(
scanBasePackages={"CRUDEMongo.class"})
public class Demo3Application{
    public static void main(String[] args) {
        SpringApplication.run(Demo3Application.class, args);
        String connectionString = "mongodb+srv://torben:<password>@cluster0.orswsxw.mongodb.net/?retryWrites=true&w=majority";
        ServerApi serverApi = ServerApi.builder().version(ServerApiVersion.V1).build();
        MongoClientSettings settings = MongoClientSettings.builder().applyConnectionString(new ConnectionString(connectionString)).serverApi(serverApi).build();
        System.out.println("Hello");
        Test test2 = new Test();
        test2.print();
        try(MongoClient client = MongoClients.create(settings)){
        }
    }
}
`

My autowired fields are null. Why is that? Because I called Test test2 with new Test()? That shouldnt made a difference because the Constructor of Test2 is not called by new. What is my mistake?

All my autowired fields are 0

Hans
  • 11
  • 4
  • 1
    when you call "new Test()", the created instance is not managed by Spring container. you could *autowired* the instance in your Demo3Application instead.
    
    @Autowired
     private Test test2
    
    Also please make sure "CRUDEMongo.class" is the same package as com.example.demo3
    – Stone Jul 28 '23 at 23:11
  • Thank you very much, that worked for me. – Hans Jul 28 '23 at 23:18

0 Answers0