【问题标题】:How are injected these classes into my Spring controller class?如何将这些类注入我的 Spring 控制器类?
【发布时间】:2015-08-20 11:48:01
【问题描述】:

我是 Spring 的新手,我对如何将一些类注入控制器类有一些疑问。

在我的项目中,我有这个 HomeController 类:

@Controller
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    @Autowired
    private MessageSource  messageSource;
    @Autowired
    private Environment env;

    .....................................................
    .....................................................
    .....................................................
}

我的疑问与 MessageSource messageSourceEnvironment env 类这 2 个对象有关。

如您所见,这些类是由 @Autowired 注释注入的。

问题是我没有在这些类的 XML 配置中定义 bean。那么为什么会正确注入呢?这些bean的定义在哪里?

Tnx

【问题讨论】:

  • 请也发布您的 xml 配置和 beans 定义(我很确定他们正在使用注释定义自己)
  • 你能显示导入语句吗?
  • Bean 不仅可以在 xml 中定义,还可以使用注解来定义,例如 @Service。如果容器找到一个匹配给定类或接口的,它会正确地注入它。

标签: java spring spring-mvc annotations spring-annotations


【解决方案1】:

bean 的自动发现基于以下规则:

1) 在 spring-config.xml 中使用 context:annotation-config 标签让 Spring 使用注解
2) 使用 context:component-scan 标签 spring-config.xml 并告诉 Spring 要在其中查找的包 自动发现 bean
3)使用@Component注解标记一个类 作为 Spring 自动发现的 bean

如果使用@Component annotation,则bean声明不需要在spring-config.xml中声明

【讨论】:

    【解决方案2】:

    Spring 映射可以使用XMLannotations 完成。

    在你的情况下,如果没有定义 XML,你的 MessageSourceEnvironment 类应该由 Spring annotations 映射,如 @Component @Service@Resource

    @Component

    表示一个带注释的类是一个“组件”。在使用基于注释的配置和类路径扫描时,此类类被视为自动检测候选对象

    @Autowired

    @Autowired 注释将尝试在 spring 上下文中查找 Foo 类型的 bean,然后将其注入。

    @Resource

    与此类似的是@Resource 注解,它将尝试查找名称为“foo”的 bean。总而言之,@Autowired 按类型连线,@Resource 按名称连线。

    【讨论】:

      【解决方案3】:

      EnvironmentMessageSource 都与 Spring Framework 的内部工作密切相关。

      环境是应用程序上下文的一部分,可用于自动装配。

      ApplicationContext 接口扩展了 MessageSource 接口,并且可以作为消息源自动装配,即使您尚未定义自己的消息源 bean。 (如果定义自己的消息源,应用上下文将delegate to that

      【讨论】:

        猜你喜欢
        • 2019-03-05
        • 1970-01-01
        • 2018-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        相关资源
        最近更新 更多