Understanding AutoWired Behavior of Spring

Asked 2 years ago, Updated 2 years ago, 85 views

Hello, I'm writing to ask for your advice.

@Service
public class Parent1 extensions Child {
    // This is just a definition.
}

public class Child extensions BaseChild {
    // This is where we call the base call.
}

public class BaseChild {
    public void aMethod() {
        Create c=new Create();
        // make a method call for c
    }
}

I forgot a little about the above configuration, but
There must have been an abstract somewhere...

@Component
public class Create {
    @ AutoWired
    Properties prop;
}

@Spring Settings for Autowired

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>/WEB-INF/resources/test.properties</value>
    </list>
  </property>
</bean>

Processing in BaseChild instantiates another class Create
I'm calling the method

Properties you are trying to use in an instantiated class I'm having trouble injecting with AutoWired.


on a single class Parent 2 that does not have a configuration like Parent1 AutoWired will inject it properly, so
It seems unlikely that the description is wrong...
I don't have much experience with Spring, so please let me know.

java spring

2022-09-29 21:51

1 Answers

Perhaps, when you let Parent2 perform the intended operation, @Autowired injected the Create class.

public class Parent2{
    @Autowired
    Create c;
    public void hogeMethod() {
        // method call in c
    }
}

Similarly, BaseChild should be the desired behavior if Create is injected with @Autowired.

Only bean managed by spring injects value objects without permission, and @Autowired in self-new objects is not automatically injected.

NOTE: Based on the information that @Service is given, Parent1 and Parent2 appear to be managed by spring as bean in your running environment.

FWIW—Tried to see if Autowired is possible in the base class ->https://github.com/Yuki-Inoue/test-mvn-autowired


2022-09-29 21:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.