如何在春天使用@Autowired [英] How to use @Autowired in spring

查看:186
本文介绍了如何在春天使用@Autowired的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的spring.xml如下所示

my spring.xml is as below

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd

">
    <context:component-scan base-package="com.mkyong.service" />
    <context:annotation-config />

</beans>

我有Test1类

package com.mkyong.service;

import org.springframework.stereotype.Component;
@Component("test1")
public class Test1 {
public int i=1;
}

我有一个App类

package com.mkyong.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mkyong.service.Test1;

public class App 
{
    @Autowired
    Test1 test1;

    public static void main( String[] args )
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "spring.xml");
        App app=new App();

        System.out.println(app.test1);
    }

}

但我输出为null我不能正确地自动装配它。我做错了什么?

But I get the output as null.I can not Autowire it properly.Where I am doing wrong?

推荐答案

当你这样做时:

App app=new App();

它创建了一个不受Spring管理的App新实例,因此你没有自动装配的组件。

It creates a new instance of App that is NOT managed by Spring, hence you wont have the autowired components.

您需要在spring xml中声明App bean,然后使用 context.getBean(beanName)

You need to declare the App bean in the spring xml and then retrieve it using context.getBean("beanName")

例如在Spring XML中,您可以将bean声明为:

E.g. in the Spring XML you can declare the bean something like this:

<bean id="app" class="com.mkyong.common.App" />

然后使用 context.getBean(app)然后它将拥有Autowired组件。

and then retrieve it back with context.getBean("app") then it will have the Autowired components.

这篇关于如何在春天使用@Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆