一,bean的装配
bean是依赖注入的,通过spring容器取对象的。
装配方法有:
前面两种没什么好讲的,就改改参数就好了。
这里重要讲注解。
注解的主要类型见图,其中component是bean,repository,service,controller都是spring中的DAO层,service层和controller层的bean,autowired和resourcey用来对bean的属性进行标注。
一个注解的例子:
package com.itheima.annotation; public interface UserDao { public void save(); } package com.itheima.annotation; @Repository("userDao") 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(){ System.out.println("userservice...save.."); } }
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..."); } }
xml配置文件配置context的属性
<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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.1.xsd 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 /> <bean id = "userDao" class = "com.itheima.annotation.UserDaoImpl"/> <bean id = "userService" class = "com.itheima.annotation.UserServiceImpl"/> <bean id = "userController" class = "com.itheima.annotation.userControllerImpl"/> </beans>
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...");}}