注解需要用到context标签
去Spring
\spring-framework-4.1.6.RELEASE\docs\spring-framework-reference\html 最下面的
找到
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->
</beans>
替换原本的xml中的开头
IOC中的注解
在xml中加上
<context:component-scan base-package=" 包名 "/>
就可用了
@Component(" bean_name ")
加在类上面,起的名字在
getBean(“ bean_name ”)直接调用
@Autowired
在对象上 自动去找对应类型的类
在另一个类上@Repository(" otherbean_name")
想指定这个别名,强制按照名称注入
@Autowired
@Qualiufier(" otherbean_name")
上面的两个
@Autowired
@Qualiufier(" otherbean_name")
等于 @Resource(name=" otherbean_name")
实现
1Annotation
@Component("anno")
public class Annotation1 {
// @Autowired
// @Qualifier("annoDao")
@Resource(name="annoDao")
private AnnotationDao dao;
public void save(){
System.out.println("annotation 保存");
dao.save();
}
@Value("玉米")
private String something;
public String sayhello(String name){
return "hello" +name;
}
2.AnnotationDao
@Repository("annoDao")
public class AnnotationDao {
public void save(){
System.out.println("Dao 保存");
}
}
3Test
public class SpringDemo1 {
@Test
public void demo11() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml"
);
Annotation1 a = (Annotation1) context.getBean("anno");
String s = a.sayhello("Spring Annotation");
a.save();
System.out.println(s);
}
}
其他注解
@PostConstruct
@PreDestory
回到了bean的十一级台阶
使用.close() 只能ClassPathXmlApplicationContext
ApplicationContext没有这个方法
Bean的 作用范围注解
@Component(“bean2”)
@Scope(“prototype”) 多例,地址不同 默认单例不用设置
注解与XML混合使用
单独使用属性注入
xml中的:
<context:annotation-config />
<context:annotation-config />
<bean name="Abean" class="com.annotation.demo3.A">
<!-- <property name="aDao" ref="ADaobean"/>
<property name="b" ref="Bbean"/>-->
</bean>
<bean name="Bbean" class="com.annotation.demo3.B">
</bean>
<bean name="ADaobean" class="com.annotation.demo3.ADao">
</bean>
A类
public class A {
@Resource(name = "B")
private B b;
@Resource(name="ADao")
private ADao aDao;
public void hello(){
System.out.println(" A hello 执行了");
b.hello();
aDao.hello();
}
ADao
@Repository("ADao")
public class ADao {
public void hello(){
System.out.println(" ADao hello 执行了");
}
}
B类
@Repository("B")
public class B {
public void hello(){
System.out.println(" B hello 执行了");
}
}