我的applicationContext.xml:

<bean id="studentService" class="com.coe.StudentService">
    <property name="studentProfile" ref="studentProfile" />
</bean>

<bean id="studentProfile" class="com.coe.student.StudentProfile">

</bean>


我的web.xml:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>


我的课程:

StudentService{
private StudentProfile studentProfile;
//has appropriate getters/setters


}

StudentProfile{
private String name;
//has getter/setter


}

我有一个jsp调用studentService.studentProfile.name,并且错误显示studentProfile为null

我的假设是,当服务器启动时,Spring会根据请求实例化所有对象,因此,在调用StudentService时,Spring还会设置StudentProfile吗?

最佳答案

如果您愿意使用注释,它实际上不是问题的答案,而是可能的解决方案:

Web.xml

<!-- Spring -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>spring.xml</param-value>
</context-param>


Spring.xml

<context:component-scan base-package="com.coe" />


Java代码

@Service
StudentService{
@Autowired
private StudentProfile studentProfile; }

@Repository//???
StudentProfile{
private String name;}


也就是说,我很难理解为什么StudentProfile将是一个bean(假设每个学生都有一个配置文件),而StudentService将引用单个StudentProfile,但这可能只是您的术语。(或者我对此缺乏理解)

09-19 05:54