Spring Bean和@Autowired构造函数与params

时间:2012-11-08 12:33:02

标签: java spring javabeans autowired

我想了解是否可以使用以及如何使用@Autowired Constructor和params执行Bean。

@Component
public class Routes
{
    private Foo req;

    @Autowired
    public Routes(Foo req)
    {
        this.req = req;
    }
    public String getUrl(String destin)
    {
        return req.getContextPath() + destin;
    }
}

@Component
public class HomeController
{
    @Autowired
    private Routes routes;

    public HomeController(Foo req)
    {
        String foo = routes.getUrl("something");
    }
}

真实代码------编辑--------------- 例外情况发生在线上: String foo = rt.getUrl(“caca”);

public class AppRun extends HttpServlet {

    private static final long serialVersionUID = -3308874705513248491L;

    private ApplicationContext context;

    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

        FooTest ft = new FooTest();

        HomeControllerTest hc = (HomeControllerTest) context.getBean("homeControllerTest", new Object[]{ft});
    }
}

@Component
@Scope("prototype")
public class FooTest {

    public String mensagem()
    {
        System.out.println("funcionou");
        return "ok";
    }

}

@Component
@Scope("prototype")
public class RoutesTest {

    private FooTest req;

    @Autowired
    public RoutesTest(FooTest req)
    {
        this.req = req;
    }

    public String getUrl(String destin)
    {
        return req.mensagem().concat(destin);
    }

}

@Component
@Scope("prototype")
public class HomeControllerTest {

    @Autowired
    private RoutesTest rt;

    public HomeControllerTest(FooTest req)
    {
        String foo = rt.getUrl("caca");

        System.out.println(foo);
    }

}

1 个答案:

答案 0 :(得分:5)

问题是您正在构造函数中访问尚未估值的属性:Spring必须先创建对象,然后才能设置@Autowired属性rt。将参数RoutesTest rt添加到构造函数中,或将构造函数逻辑移动到afterPropertiesSet方法。

以下是如何使用构造函数更改失败的类:

@Component
@Scope("prototype")
public class HomeControllerTest {

    private RoutesTest rt;

    @Autowired
    public HomeControllerTest(FooTest req, RoutesTest rt)
    {
        this.rt = rt;
        String foo = rt.getUrl("caca");

        System.out.println(foo);
    }

}