Spring 3.0中@Autowired注入Address对象时出现空指针异常求助
Hey there! Let's walk through why your Address bean is coming up null and that "Default Constructor E..." message is showing up—these are common gotchas for Spring newbies, so we'll fix this step by step.
First, Let's Cover the Most Likely Culprits
1. Your Address class isn't registered in the Spring Container
Spring can only inject beans that it manages. If Address isn't marked as a Spring-managed bean, @Autowired has nothing to inject. Here's how to fix this:
- Add a stereotype annotation like
@Componentto yourAddressclass:@Component public class Address { // Your fields, constructors, and methods here } - Or, if you're using XML configuration, define the
Addressbean explicitly in yourapplicationContext.xml:<bean id="address" class="com.yourpackage.Address"/>
2. You're manually instantiating Employee instead of getting it from Spring
That "Default Constructor E..." message is a big clue here. If you're writing code like Employee emp = new Employee();, Spring has no way to inject the Address bean—because Spring only handles dependency injection for beans it creates itself.
Instead, you need to fetch the Employee bean from the Spring application context:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Employee emp = context.getBean(Employee.class);
3. You haven't enabled annotation support in your Spring config
Spring 3.0 requires explicit configuration to recognize @Autowired and other annotations. Add these lines to your XML config:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Enable processing of annotation-based dependencies --> <context:annotation-config/> <!-- Scan your package for stereotype annotations like @Component --> <context:component-scan base-package="com.yourpackage"/> </beans>
4. Double-check your Employee class setup
Make sure Employee itself is a Spring-managed bean (add @Component or define it in XML), and that the Address field has the @Autowired annotation correctly applied:
@Component public class Employee { @Autowired private Address address; public Employee() { System.out.println("Default Constructor E..."); } // Add a getter to test the injected Address public Address getAddress() { return address; } }
Quick Test to Verify
Once you've made these changes, run your main class again using the context to fetch Employee. If everything is set up right, emp.getAddress() should no longer be null.
内容的提问来源于stack exchange,提问作者Shubham Goswami

