基于annotation的spring注入

  1. 配置文件beans.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.xsd
                                http://www.springframework.org/schema/context
                                http://www.springframework.org/schema/context/spring-context.xsd">
        <!-- 打开annotation功能 -->
        <context:annotation-config/>
        <!-- 设定读取annotation的范围 -->
        <context:component-scan base-package="com.gcflowers.spring"/>
           
    </beans>
  2. 在类上使用component("xx")来代替<bean id="xx" class="xxx.xx"></bean>,依次为每个类添加@Component("xx")如:
    @Component("userDao")
    public class UserDao implements IUserDao {

        public void add(User user) {
            System.out.println("add");
        }

        public void delete(int id) {
            System.out.println("delete");

        }

        public User load(int id) {
            return new User(1,"zc");
        }

    }
  3. 在类的set方法上使用@Resource来注入,如:
    @Component("userAction")
    @Scope("prototype")
    public class UserAction {

        private IUserService userService;
        private User user;
        private int id;
        
        public void add(User user){
            userService.add(user);
        }
        
        public void delete(){
            userService.delete(id);
        }
        
        public void load(){
            userService.load(id);
        }

        public IUserService getUserService() {
            return userService;
        }
        
        //默认按名称
        @Resource
        public void setUserService(IUserService userService) {
            this.userService = userService;
        }

        public User getUser() {
            return user;
        }

        public void setUser(User user) {
            this.user = user;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
        
    }
  4. 一般使用@Controller("xxAction"),@Repository("xxDao"),@Service("xxService")来代替@component("xx"),
原文地址:https://www.cnblogs.com/charleszhang1988/p/3045967.html