Java:spring框架(2)IOC注解
2017-01-11 本文已影响0人
梦之志
一.创建XML文件,配置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">
<!-- bean definitions here -->
<!--开启注解扫描-->
/*
* 1. base-package属性: 设置包名,程序将会在设置的包里面扫描注解
*/
<context:component-scan base-package="com.company"></context:component-scan>
</beans>
二.创建User类,设置类注解
/*
* 1. 设置类注解方式: @Component(value = "user")
@Service(value="user")
* 2. value属性: 随意设置,标记注解类
*/
//@Component(value = "user")
@Service(value = "user")
public class User {
public void UserTest(){
System.out.println("我是User");
}
}
三.创建UserService类,设置属性注解
/*
* 1. 设置属性注解方法: @Autowired //自动装载,自动扫描属性
@Resource(name = "userDao")
* 2.name 属性: 随意设置,标记注解属性
*/
@Component("userService") //装载类
public class UserService {
// @Autowired //自动装载
@Resource(name = "userDao") //装载属性
private UserDao userDao;
public void ServiceTest(){
System.out.println("我是UserService");
//通过属性注解获取的类对象,调用类方法
userDao.UserDaoTest();
}
}
@Service("userDao")
public class UserDao {
public void UserDaoTest(){
System.out.println("我是UserDao");
}
}
四.创建测试类,编写代码实现
/*
* 1.使用ApplicationContext加载XML配置文件
* 2.通过getBean()方法以及类注解中的value值,获取对应的类对象
*/
ApplicationContext context = new ClassPathXmlApplicationContext("springUser");
User user = (User) context.getBean("user");
user.UserTest();
//使用注解装载对象
UserService userService = (UserService) context.getBean("userService");
userService.ServiceTest();