提示:
文章目录
spring注解@Autowired实现自动装配的步骤
1、引入依赖
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
xmlns:context="http://www.springframework.org/schema/context"
spring核心配置文件bean.xml中加入此依赖
2、开启注解扫描组件
<context:component-scan base-package="com.autowired"></context:component-scan>
spring注解默认是关闭的状态,需要手动设置开启,base-package="com.autowired"表示注解开启的包路劲,
3、使用注解@Controller //标注在表示层类上@Service //标注在业务层的类上@Repository //标注在持久层的类上完成bean对象创建
package com.autowired.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao {
}
等同于基于xml管理创建bean对象
<bean id="userDaoImpl " class="package com.autowired.dao.UserDaoImpl">
等同于:
UesrDao user=new UserDaoImpl();//创建对象
其他
UserServiecImpl层使用@Service创建对象
UserController层使用@Controller创建对象
三者写入的方式不同但是原理一样;
4、@Autowired注入,默认类型ByType自动装配
@Autowired注解:根据属性类型找到对应的对象完成注解
代码
1、dao
package com.autowired.dao;
public interface UserDao {
public void add();
}
package com.autowired.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao {
public void add() {
System.out.println("dao------");
}
}
2、service
package com.autowired.service;
public interface UserService {
public void add();
}
package com.autowired.service;
import com.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
//1.开启注解组件扫描
//2.注解创建对象 @Service @Controller @Repository
//注入dao层
@Autowired
//第一种方式:属性注入---根据类型找到对应的对象完成注入
private UserDao userDao;
public void add() {
System.out.println("service---------");
//调用UserDao中的方法
userDao.add();
}
}
3、controller层
package com.autowired.controller;
import com.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
//注入service层
//第一种方式:属性注入
@Autowired//根据类型找到对应的对象完成注入
private UserService userService;
public void add(){
System.out.println("controller------");
//调用service接口中的方法
userService.add();
}
}
4、测试类:
package com.autowired;
import com.autowired.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestUserController {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
UserController controller = context.getBean(UserController.class);
//调用controller中add方法
controller.add();
}
}
例如代码中三层中将来@Autowired放在属性上,进行属性注入