为什么我的spring注解不管用?
问题描述:
public class TestDrive {
@Resource(name="emp")
Emp e ;
public static void main(String[] args) {
System.out.println(new TestDrive().e);
}
}
答
1.首先,运行时注解需要通过反射才能使用
2.spring内部调用时封装了,所以注解能直接反应出来。
你的问题在于:
1.你的类没有配置spring的Component
2.想要spring使用你配置的注解,你的bean就不能自己new,需要从spring的上下文获取代理bean才可以。
希望能够帮到你....
答
xml里面的配置:
/context:component-scan
<!-- 开启注解 -->
context:annotation-config/
<bean id="emp" class="springdemo2.Emp">
<property name="ename" value="jijie"/>
</bean>
答
``` <context:component-scan base-package="*"></context:component-scan>
<!-- 开启注解 -->
<context:annotation-config/>
<bean id="emp" class="springdemo2.Emp">
<property name="ename" value="jijie"/>
</bean>
答
@Component
public class TestDrive {
@Resource(name="emp")
Emp e ;
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println(((T)ac.getBean("t")).e );
System.out.println(new TestDrive().e);
}
}
@Component(value="t")
class T {
@Resource(name="emp")
Emp e ;
}
这么着可以了