配置文件和注解混合使用
- 创建对象操作使用配置文件方式实现
- 注入属性的操作使用注解方式实现
编写BookDao.java和OrderDao.java文件
BookDao.java
1 package com.example.spring; 2 3 public class BookDao { 4 public void book(){ 5 System.out.println("Book Dao."); 6 } 7 }
OrderDao.java
1 package com.example.spring; 2 3 public class OrderDao { 4 public void order(){ 5 System.out.println("Order Dao."); 6 } 7 }
创建对象操作使用配置文件方式实现
编写配置文件Beans.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 9 10 <!--开启注解扫描,到包里面扫描类、方法、属性上面是否有注解--> 11 <context:component-scan base-package="com.example.spring"></context:component-scan> 12 13 <!-- 在配置文件中创建对象 --> 14 <bean id="bookService" class="com.example.spring.BookService"></bean> 15 <bean id="bookDao" class="com.example.spring.BookDao"></bean> 16 <bean id="orderDao" class="com.example.spring.OrderDao"></bean> 17 18 </beans>
注入属性的操作使用注解方式实现
编写BookService.java
1 package com.example.spring; 2 3 import javax.annotation.Resource; 4 5 public class BookService { 6 //注解方式注入属性,得到对象 7 @Resource(name = "bookDao") 8 private BookDao bookDao; 9 10 @Resource(name = "orderDao") 11 private OrderDao orderDao; 12 13 public void service(){ 14 System.out.println("Book Service."); 15 //调用方法 16 bookDao.book(); 17 orderDao.order(); 18 } 19 }
编写Application.java
1 package com.example.spring; 2 3 import org.springframework.context.support.AbstractApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class Application { 7 public static void main(String[] args) { 8 //bean配置文件所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml 9 //使用AbstractApplicationContext容器 10 AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml"); 11 //得到配置创建的对象 12 BookService bookService = (BookService) context.getBean("bookService"); 13 bookService.service(); 14 } 15 }
运行输出
Book Service. Book Dao. Order Dao.
时间: 2024-11-07 00:58:22