1.引用jar包aop的jar包
2.配置文件使用包扫描
<context:component-scan base-package="com.zhiyou100.sh"></context:component-scan>
3.在相应的类加上注解
@Repository 持久化注解。
@Service 业务层注解
@Controller 控制层注解
@Autowired 自动注入 按照类型帮你自动注入,如果由多个类型相同的那么就会在按照名称注入。(建议使用这个)
@Resouce 自动注入 按照名称注入,如果没有相同名称的bean那么会按照类型帮你注入。 它可以指定名称来注入。
controller的代码
Service的代码
dao的代码
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="UserDao" class="com.zhiyou100.sh.dao.UserDao"/> <bean id="UserService" class="com.zhiyou100.sh.service.UserService"> <property name="dao" ref="UserDao"></property> </bean> <bean id="UserController" class="com.zhiyou100.sh.controller.UserController"> <property name="service" ref="UserService"></property> </bean> </beans>
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zhiyou100.sh.controller.UserController; public class test { public static void main(String[] args) { ApplicationContext app=new ClassPathXmlApplicationContext("app.xml"); UserController bean = (UserController) app.getBean("UserController"); bean.selectByid(1); } }
<?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-4.2.xsd"> <context:component-scan base-package="com.zhiyou100.sh"></context:component-scan> </beans>
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zhiyou100.sh.controller.UserController; public class test1 { public static void main(String[] args) { ApplicationContext app=new ClassPathXmlApplicationContext("app1.xml"); UserController bean = (UserController) app.getBean("UserController"); bean.selectByid(1); } }