Spring: how to assure that a class is created only by spring, and not by the new keyword

Is it possible to guarantee that only spring can instantiate the class and not by keyword newat compile time? (To avoid creating an instance by accident)

Thank!

+3
source share
7 answers

If you want to detect it at compile time, the constructor must be non-public. The private one is probably too strict (it makes the code analysis tools suggest that it will never be called and may even trigger warnings in some IDEs), I would say that it is best to use the default (without the modifier protected by the package). In cases where you want to allow subclasses in other packages (but this is not possible without allowing the constructor to be called directly from this subclass), you can protect it. Be sure to comment the constructor accordingly, so anyone who reads the code understands why the constructor is like this.

Spring will invoke this non-public constructor without any problems (since Spring 1.1, SPR-174 ).

, - , Spring ( ) , .

/ ( Spring), . , , , , Spring, .

, , , .

, ( , Spring), , , factory ( , createManuallyInitializedInstance - ).

: - , . , ( , ), . : , .

+6

, , - Runtime ; Spring Java (.. , Spring, Java - ). , :

//CONSTRUCTOR
public MyClass() {
    try {
         throw new RuntimeException("Must be instantiated from with Spring container!");
    }
    catch (RuntimeException e) {
        StackTraceElement[] els  = e.getStackTrace();
        //NOW WALK UP STACK AND re-throw if you don't find a springframework package
        boolean foundSpring = false;
        for (StackTraceElements el : els) {
            if (el.getDeclaringClass().startsWith("org.springframework")) {
                foundSpring = true; break;
            }
        }
        if (!foundSpring) throw e;
    }
}

!

+5

, , Spring, . . , . , DI, , , , - . , , DI, .

+1

, - . , , .

+1

, Spring , , Spring , IOC , - , , IOC . , ( ), .

, , -

0

, Spring

0

spring, , public static YourClass getInstance() , . , getInstance().. Spring. , "" Spring...

-1

Source: https://habr.com/ru/post/1737664/


All Articles