1、特定的组件包含:
-@Component:基本注解,标识了一个受Spring管理的组件
-@Repository:标识持久层组件
-@Service:标识业务层组件
-@Controler:标识表现层组件
他们之间是可以混用的。
2、在bean的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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- <bean id="helloWorld" class="spring.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>-->
<context:component-scan base-package="spring.annotations"></context:component-scan>
</beans>
3、创建controller类添加@Controller 注解
package spring.annotations.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import spring.annotations.service.UserService;
@Controller
public class UserController {
@Autowired
UserService userService;
public void execute(){
System.out.println("UserControler Executor");
userService.add();
}
}
4、创建service类,添加@Service 注解
package spring.annotations.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void add(){
System.out.println("UserService add");
}
}
5、创建repository类,添加Repository注解
package spring.annotations.repository;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepositoryImpl implements UserRepository {
@Override
public void save() {
System.out.println("save user");
}
}
6、编写测试类
package spring.annotations;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring.annotations.controller.UserController;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
TestObject obj = (TestObject) context.getBean("testObject");
System.out.println(obj);
UserController controler = (UserController) context.getBean("userController");
controler.execute();
}
}