【问题标题】:how do you inject a bean into a @Controller class如何将 bean 注入 @Controller 类
【发布时间】:2023-04-09 03:59:02
【问题描述】:

我对 Spring 有点陌生(使用 3.0),所以我希望有一个简单的答案。如果我有一个带有@Controller@RequestMapping 注释的控制器,并且我想通过依赖注入设置一个属性,我该怎么做呢?控制器类不必出现在 Spring 配置文件中,因为 @Controller 注释会自动获取它。

示例控制器类:

package gov.wi.dnr.wh.web.spring;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class RehabHomeController {
  private String xxx;

  @RequestMapping(value="/rehab/home", method = RequestMethod.GET)
  public String get() {
    return "whdb.rehabhome";
  }

  public String getXxx() {
    return xxx;
  }

  public void setXxx(String xxx) {
    this.xxx = xxx;
  }
}

弹簧配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                            http://www.springframework.org/schema/context 
                      http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
  </bean>

  <context:component-scan base-package="gov.wi.dnr.wh.web.spring"/>
  <mvc:annotation-driven />

</beans>

这按原样工作,但我想注入“xxx”属性。我该怎么做呢?

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:
    @Autowired
    private YourService yourServiceBean;
    

    (你也可以使用@Inject

    当然,YourService 必须声明为 bean - 在 applicationContext.xml 中或通过注释(例如 @Service

    如果要注入字符串属性,可以使用@Value注解:

    @Value("${propName}")
    private String str;
    

    (为此,您需要PropertyPlaceholderConfigurer

    【讨论】:

    • 谢谢。如果我只是想注入一个值为“hello”的字符串,它在 applicationContext.xml 文件中的外观如何?
    • 您好,谁能告诉我如何在没有自动装配的情况下做到这一点,基本上我不希望我的变量名依赖于 bean。
    • 如果服务是在mvc-config.xml中定义的,它是否工作?我正在尝试将 mvc-config.xml 中定义的 bean 注入组件类中,它不起作用。
    猜你喜欢
    • 2014-01-24
    • 2019-02-03
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2019-10-25
    • 2013-04-05
    相关资源
    最近更新 更多