【问题标题】:How to autowired third part bean to my @Controller bean如何将第三方 bean 自动装配到我的 @Controller bean
【发布时间】:2023-03-05 13:31:01
【问题描述】:

我想将我的 spring 应用程序的 xml 配置替换为注释样式。

我有这样的@Controller:

@Controller

@RequestMapping("/events")

public class EventController extends AbstractController{
    @Autowired
    EventService eventService;


    Jaxb2Marshaller refMarsh;

    /// 
}

在我有这样的 xml 配置之前:

<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
            <list>
                <value>com.epam.hhsystem.model.candidate.Candidate</value>
                <value>com.epam.hhsystem.model.vacancy.Vacancy</value>
                <value>com.epam.hhsystem.model.event.Event</value>
            </list>
        </property>
    </bean>

    <bean id="eventController" class="com.epam.hhsystem.ws.controller.EventController">
        <property name="jaxb2Mashaller" ref="refMarsh" />
    </bean>

</beans>

我用注释样式替换了 thirst bean:

@Configuration
public class ContextConfiguration {



    @Bean(name = "refMarsh")
    public Jaxb2Marshaller jaxb2Marshaller() {
        Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
        jaxb2Marshaller.setClassesToBeBound(Event.class);
        jaxb2Marshaller.setClassesToBeBound(Candidate.class);
        jaxb2Marshaller.setClassesToBeBound(Vacancy.class);
        return jaxb2Marshaller;
    }
}

如何替换第二个bean?

【问题讨论】:

    标签: xml spring annotations


    【解决方案1】:

    可能你想要这个:

        @Bean(name = "eventController")
        public EventController getEventController(@Qualifier("refMarsh") Jaxb2Marshaller marshaller) {
            EventController controller = new  EventController();
            controller.setJaxb2Mashaller(marshaller);
            return controller;
        }
    

    【讨论】:

    • 我可能有什么不明白的地方。我有NPE。这是我更详细的代码: public abstract class AbstractController { protected Jaxb2Marshaller jaxb2Mashaller;公共无效 setJaxb2Mashaller(Jaxb2Marshaller jaxb2Mashaller) { this.jaxb2Mashaller = jaxb2Mashaller; ///... }
    • 我认为,当我在配置中创建 EventController - 它是另一个 EventController,而不是在检测到 @Controller 公共类 EventController 时创建 Spring ...
    • 请提供完整的堆栈跟踪和代码。例如,您可以发布here
    • 如果您在配置中声明单独的 bean(使用 @Bean)并作为单独的类(使用 @Controller),那么它可能是上下文中的两个对象。所以我不明白你为什么在配置类中需要它......
    • 我回答最后一条评论:
    【解决方案2】:

    关键是你是如何配置网络配置的,你是使用“WebApplicationInitializer”还是带有监听器的 web.xml,然后在配置中你可以扩展 WebMvcConfigurerAdapter 或使用@EnableWebMvc,请查看这些 YT 视频

    http://www.youtube.com/watch?v=-pV351E_stM

    编辑 2: 好的,您添加了@ComponentScan 并添加了控制器的包吗?在视频中你必须使用@ComponentScan

    【讨论】:

    • 这个视频很有趣。但是没有人将第三方 bean 自动装配到 @Controller
    • 我在ContextConfiguration类中添加了@EnableWebMvc,但是并没有带来改变
    • 我有 jaxbMarshaller 的 NPE
    猜你喜欢
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2012-10-02
    • 2011-01-23
    • 2015-04-11
    • 2019-03-28
    相关资源
    最近更新 更多