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

2025-11-08 01:30:33

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提供的标准装配注解。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢