注意,还要配置才能获得下面要用到的提示
配置文件applicationContext.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 配置注解驱动与包扫描
context:component-scan:组件扫描 -->
<context:component-scan base-package="cn.java.annotation.ioc1"></context:component-scan>
</beans>
package cn.java.annotation.ioc1;
import org.springframework.stereotype.Component;
@Component("ya")
public class Duck {
private String duckName="唐老鸭";
private Integer age=20;
public String getDuckName() {
return duckName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public void setDuckName(String duckName) {
this.duckName = duckName;
}
}
package cn.java.annotation.ioc1;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//@Component(value="smallJi")相当于在配置文件创建一个id为smallJi的bean对象,在springMVC中可以直接写成Component
@Component(value="smallJi")//可以直接写成:@Component("smallJi")
@Scope(value="singleton")//相当于创建一个bean而且是单例。@Scope("singleton")
public class Ji {
//@Resource(name="ya") 将Duck的属性赋给Ji
@Autowired//可以直接这样写,可以直接找到Duck属性并赋给Ji
private Duck duck;
public void behavior() {
System.out.println("打鸣="+duck);
}
}调用结果: