package com.itheima.annotation;
public interface UserDao {
public void save();
}
package com.itheima.annotation;
import org.springframework.stereotype.Repository;
@Repository("userDao") //DAO层的类标识为bean
public class UserDaoImpl implements UserDao{
public void save(){
System.out.println("userdao实现的...save...");
}
}
package com.itheima.annotation;
public interface UserService {
public void save();
}
package com.itheima.annotation;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
@Service("userService")
public class UserServiceImpl implements UserService{
@Resource(name="userDao")
private UserDao userDao;
public void save() {
this.userDao.save();
System.out.println("userservice服务层....save..."+this.userDao);
}
}
package com.itheima.annotation;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
@Controller("userController")
public class UserController {
@Resource(name="userService")
private UserService userService;
public void save(){
this.userService.save();
System.out.println("userController...save..."+this.userService);
}
}
<?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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 使用 context 命名空间 ,在配置文件中开启注解处理器 -->
<context:annotation-config />
<!--分别定义3个Bean实例:此时不再需配置<property>子元素了 -->
<bean id="userDao"
class="com.itheima.annotation.UserDaoImpl" />
<bean id="userService"
class="com.itheima.annotation.UserServiceImpl" />
<bean id="userController"
class="com.itheima.annotation.UserController" />
</beans>
package com.itheima.annotation;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnotationAssembleTest {
public static void main(String[] args) {
String xmlPath = "com/itheima/annotation/beans6.xml";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath); //通过Spring容器加载配置文件
UserController userController =
(UserController) applicationContext.getBean("userController");// 获取UserController实例
// 调用UserController中save()
userController.save();
}
}