使用@Resource和@Inject注解自动装配Spring组件

 时间:2026-02-15 22:34:37

1、Spring还支持使用@Resource和 @Inject给Spring注册组件。

@Resource默认是按照组件名称进行装配的。

package com.gwolf.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.gwolf.dao.BookDAO;

@Service

public class BookService {

        @Resource

        private BookDAO bookDAO;

        

        public void print() {

                System.out.println(bookDAO);

        }

        

}

使用@Resource和@Inject注解自动装配Spring组件

2、执行junit测试类,查看使用@Resource注入的组件能够注入成功。

package com.gwolf.test;

import org.junit.Test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.gwolf.config.MainConfigOfAutowired;

import com.gwolf.service.BookService;

public class ComponentTest {

        AnnotationConfigApplicationContext applicationContext = 

                        new AnnotationConfigApplicationContext(MainConfigOfAutowired.class);

        

        @Test

        public void testImport() {

                BookService bookService = (BookService)applicationContext.getBean(BookService.class);

                

                bookService.print();

                

                applicationContext.close();

        }

}

使用@Resource和@Inject注解自动装配Spring组件

3、如果要想使用@Inject注解,需要导入相关的依赖包。

<dependency>

            <groupId>javax.inject</groupId>

            <artifactId>javax.inject</artifactId>

            <version>1</version>

        </dependency>

        

使用@Resource和@Inject注解自动装配Spring组件

4、在业务层使用@Inject 注入其他的组件。

package com.gwolf.service;

import javax.annotation.Resource;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.gwolf.dao.BookDAO;

@Service

public class BookService {

        @Inject

        private BookDAO bookDAO;

        

        public void print() {

                System.out.println(bookDAO);

        }

        

}

使用@Resource和@Inject注解自动装配Spring组件

5、执行junit测试类,查看使用@Inject注入的组件能够注入成功。

使用@Resource和@Inject注解自动装配Spring组件

6、@Autowired是spring特有的自动装配注解,@Resource和@Inject是java提供的标准装配注解。

  • Spring的自动装配学习总结
  • 什么是spring的自动装配?
  • Spring学习--SpringBoot自动配置实现数据库访问
  • SpringBoot中SpringMVC自动配置原理
  • SpringBoot数据库访问自动配置原理
  • 热门搜索
    三伏天是什么意思 入党有什么好处 九价疫苗是什么意思 什么电视剧好看 end是什么意思 什么是质量 什么是自然数 快乐的反义词是什么 10月16日是什么星座 白带多有腥臭味是什么原因引起的