简体   繁体   中英

How inject a service class into a class not managed by spring

I have this situation:

public class Other {
    public void test() {
        new ClassA().process();
    }
}

public class ClassA {

    @Autowired
    private ClassB classB;

    public void process() {
        classB.executeSomething(); //--> NUllPOinter because classA was not created by spring.
    }
}


@Service
public class ClassB {
    public void executeSomething() {
        // execute something
    }
}

I tried use ApplicationContext but the problem continued.

Someone, have a idea what i should do?

Thanks.

This is always the right way to declare a class dependency (always for annotated ioc spring bean):

public class ClassA {

    private final ClassB objectB;

    public ClassA(final ClassB objectB) {
        this.objectB = objectB;
    }

    public void process() {
        objectB.executeSomething();
    }
}

In Other class, we should retrieve the singleton ClassB instance. Then it must be a bean component.

@Component
public class Other {

    private final ApplicationContext applicationContext;

    @Autowired
    public Other(final ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void test() {
        new ClassA(applicationContext.getBean(ClassB.class)).process();
    }
}

If Other class can't be a spring component, you can't retrieve the application context and then you can't inject the ClassB instance.

You can clearly autowire directly the ClassB object instance into Other component, but this example underline that you can handle bean fetching with an ApplicationContext ref.

I have this situation:

public class Other {
    public void test() {
        new ClassA().process();
    }
}

public class ClassA {

    @Autowired
    private ClassB classB;

    public void process() {
        classB.executeSomething(); //--> NUllPOinter because classA was not created by spring.
    }
}


@Service
public class ClassB {
    public void executeSomething() {
        // execute something
    }
}

I tried use ApplicationContext but the problem continued.

Someone, have a idea what i should do ?

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM