[英]How to use @Autowired in spring
我的spring.xml如下
<?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);
}
}
但是我得到的输出为空,我不能正确地自动接线,我在哪里做错了?
执行此操作时:
App app=new App();
它会创建一个不受Spring管理的App的新实例,因此您将没有自动装配的组件。
您需要在spring xml中声明App bean,然后使用context.getBean("beanName")
进行检索。
例如,在Spring XML中,您可以这样声明Bean:
<bean id="app" class="com.mkyong.common.App" />
然后使用context.getBean("app")
将其取回,它将具有自动装配的组件。
您不必使用context.getBean("beanName")
搜索bean。 这介绍
对Spring框架的不必要依赖。 那不是很干净。
最好用@Configurable
批注来批注您的App
类。
...
@Configurable
public class App
{
@Autowired
Test1 test1;
...
并在您的spring.xml文件中添加一个标签:
<context:spring-configured />
就这样。 现在,您可以根据需要创建App
类,并且自动装配将起作用。
...
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
App app=new App();
System.out.println(app.test1);
...
注意:您需要在类路径上使用spring-aspects,spring-aop,aspectjrt。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.