豆成豆注射

时间:2012-07-12 08:46:50

标签: spring

没有注入Spring bean的经验。

<beans:bean id="ModeService"
        class="<path>Service">
    <beans:property name="Mode" value="true"/>
</beans:bean>

<beans:bean id="Filter"
       class="<path>.RequestFilter">
    <custom-filter position="FIRST" />
</beans:bean>

如何将ModeService bean注入Filter bean?

好吧,我在春天注射了@William 所以:

<beans:bean id="maintenanceModeService"
        class="<path>.MaintenanceService">
    <beans:property name="maintenanceMode" value="true"/>
</beans:bean>

<beans:bean id="maintenanceFilter"
       class="<path>.MaintenanceRequestFilter">
    <custom-filter position="FIRST" />
    <beans:property name="modeService" ref="maintenanceModeService"/>
</beans:bean>

在MaintenanceService中,我附加了setter / getter来调用变量:

boolean maintenanceMode;

public void setMaintenanceMode(boolean mode)
{
    this.maintenanceMode = mode;
}

public boolean getMaintenanceMode()
{
    return maintenanceMode;
}

将setter / getter附加到MaintenanceRequestFilter:

boolean modeService;

public void setModeService(MaintenanceService maintenanceMode)
{
    this.modeService = maintenanceMode;
}

public MaintenanceService getMaintenanceMode()
{
    return modeService;
}

然后在doFilter()

中调用modeService

但是错了......

2 个答案:

答案 0 :(得分:0)

您可以使用ref属性来定义对另一个bean的引用。 Filter类应具有ModeService类型的属性,以便您可以使用<property>属性在ref标记中对其进行定义。

<beans:bean id="Filter" class="<path>.RequestFilter">
    <custom-filter position="FIRST" />
    <beans:property name="modeService" ref="ModeService"/>
</beans:bean>

答案 1 :(得分:0)

<beans:bean id="Filter" class="<path>.RequestFilter">
    <custom-filter position="FIRST" />
    <beans:property name="modeService" ref="ModService"/>
</beans:bean>

你的班级应该有一个getter / setter方法

class RequestFilter{
    public void setModeService(ModService modService){
        // some set code here
    }

    public ModeService getModeService(){
        // some set code here
        return modService;
    }
}