UserDao接口:
package com.student.annotation;
public interface UserDao {
public void say();
}
UserDaoImpl :UserDao的实现类
package com.student.annotation;
import org.springframework.stereotype.Repository;
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Override
public void say() {
System.out.println("userDao已经加载加载完成!!");
}
}
UserService:类
package com.student.annotation;
public interface UserService {
public void say();
}
UserServiceImpl:UserService的实现类:
package com.student.annotation;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource(name="userDao")
private UserDao userDao;
@Override
public void say() {
this.userDao.say();
System.out.println("userService 加载完成!!!");
}
}
UserController :
package com.student.annotation;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
@Controller("userController")
public class UserController {
@Resource(name="userService")
private UserService userService;
public void say()
{
this.userService.say();
System.out.println("UserController加载完成");
}
}
AnnotationAssembleTest:
package com.student.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnotationAssembleTest {
public static void main(String[] args) {
String xmlPath = "com/student/annotation/bean7.xml";
ApplicationContext applicationContext =new ClassPathXmlApplicationContext(xmlPath);
UserController userController =(UserController)applicationContext.getBean("userController");
userController.say();
}
}
bean7:
<?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">
<context:annotation-config/>
<!-- services -->
<bean id="userDao" class="com.student.annotation.UserDaoImpl"></bean>
<bean id="userService" class="com.student.annotation.UserServiceImpl"></bean>
<bean id="userController" class="com.student.annotation.UserController"></bean>
</beans>
运行结果:
十月 14, 2019 10:59:52 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2b71fc7e: startup date [Mon Oct 14 22:59:52 CST 2019]; root of context hierarchy
十月 14, 2019 10:59:53 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/student/annotation/bean7.xml]
userDao已经加载加载完成!!
userService 加载完成!!!
UserController加载完成