使用注解除了Spring的四个核心包和日志包,还需要导入aop包,注解可以使用在类上面,方法上面和属性上面,在xml文件中还需要引入新的约束--context
创建对象的四个注解:
1.@Component
2.@Controller web层
3.@Service 业务层
4.@Repository 持久层
注入属性注解:
1.@Autowired
2.@Resource(name=" ")
注解和配置文件混合使用
创建对象操作使用配置文件方式实现
注入属性操作使用注解方式实现
bean2.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:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- 开启注解扫描 到包里面扫面类、方法、属性上面是否有注解 --> <context:component-scan base-package="com.spring"></context:component-scan> <!-- 配置对象 --> <bean id="bookService" class="com.spring.xmlano.BookService"></bean> <bean id="bookDao" class="com.spring.xmlano.BookDao"></bean> <bean id="ordersDao" class="com.spring.xmlano.OrdersDao"></bean> </beans>
BookService.java
package com.spring.xmlano; import javax.annotation.Resource; public class BookService { //得到bookdao和orderdao的对象 @Resource(name="bookDao") private BookDao bookDao; @Resource(name="ordersDao") private OrdersDao ordersDao; public void add(){ System.out.println("service......"); bookDao.book(); ordersDao.buy(); } }
BookDao.java
package com.spring.xmlano; public class BookDao { public void book(){ System.out.println("book..."); } }
OrdersDao.java
package com.spring.xmlano; public class OrdersDao { public void buy(){ System.out.println("orderdao......"); } }
Test.java
package com.spring.xmlano; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context= new ClassPathXmlApplicationContext("bean2.xml"); BookService bookservice = (BookService) context.getBean("bookService"); bookservice.add(); } }