首先配置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: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">
<!-- 开启注解扫描 -->
<!-- 其中base-package属性指定需要扫描的基类包,spring容器将会扫描这个基类包及其子包中的所有类 -->
<!-- 当需要扫描多个包时,可以使用逗号分隔 -->
<context:component-scan base-package="com.shunli.ioc.demo4"></context:component-scan>
</beans>
在类前加上@Component(“XXX”)
package com.shunli.ioc.demo4;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
/*
* bean注解方式
*/
@Component("order")
@Scope(value = "prototype") //配置创建对象是否是以单列模式进行创建
public class Order {
//设置orderid值11111
@Value("11111")
private String orderid;
/*
@Autowired
@Qualifier("orderDao")
说明:@Autowired是按照类型去匹配,不通过@Repository("orderDao")中的orderDao进行匹配
加上@Qualifier("orderDao")则是按照orderDao匹配
也可以使用@Resource(name="orderDao")代替
*/
@Autowired
@Qualifier("orderDao")
private OrderDao orderdao;
//初始化Bean执行的方法
@PostConstruct
public void Inti() {
System.out.println("Init Bena.........");
}
//销毁Bean的方法
@PreDestroy
public void destory() {
System.out.println("destroy Bean......");
}
public void save() {
System.out.println("Order中的save");
orderdao.save();
}
public void printOrderId(){
System.out.println(orderid);
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}
}
DAO
package com.shunli.ioc.demo4;
import org.springframework.stereotype.Repository;
@Repository("orderDao")
public class OrderDao {
public void save() {
System.out.println("OrderDao中的save");
}
}
@Component是描述Spring框架中的Bean
除此之外还有:
@Controller //web层中使用
@Service //业务层
@Repository //用于对DAO实现类进行标注
这四个注解效果是一样的
测试类
package com.shunli.ioc.demo4;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class testMain {
@Test
public void demo1() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Order order = (Order)applicationContext.getBean("order");
order.save();
order.printOrderId();
applicationContext.close();
}
}