Spring DI实现方式

1.set注入

语法:1)set 方法

           2)set 配置:<property name vaule ref>

2、构造注入

语法:1)构造方法

           2)构造配置:<constructor-arg name type index value ref>

3、注解注入

(1)@Component

用于标识一个类为Spring的组件,这个类会被Spring容器管理。

代码示例:

import org.springframework.stereotype.Component;

@Component

public class MyService { }

(2)@Autowired

用于自动注入依赖。Spring会根据类型找到匹配的bean并注入。

代码示例:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

@Component

public class MyController {

        private final MyService myService;

        @Autowired

        public MyController(MyService myService) {

                 this.myService = myService;

        }

}

(3)@Qualifier

当有多个相同类型的bean时,可以使用@Qualifier指定要注入的bean。

代码示例:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.stereotype.Component;

@Component

public class MyController {

        private final MyService myService;

        @Autowired

        public MyController(@Qualifier("specificMyService") MyService myService) {

                this.myService = myService;

         }

}

(4)@Value

用于注入简单的值,比如属性文件中的配置。

代码示例:

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

@Component

public class MyConfig {

        @Value("${my.property}")

        private String myProperty;

}

(5)@Configuration和@Bean

用于定义配置类和创建bean。

代码示例:

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class AppConfig {

        @Bean

        public MyService myService() {

                return new MyService();

        }

}

(6)@PostConstruct和 @PreDestroy

用于定义对象的初始化和销毁方法。

代码示例:

import javax.annotation.PostConstruct; import javax.annotation.PreDestroy;

import org.springframework.stereotype.Component;

@Component

public class MyBean {

        @PostConstruct

        public void init() { // 初始化代码 }

        @PreDestroy

        public void cleanup() { // 清理代码 }

}

(7)@Repository

定义数据访问层Bean的注解

(8)@Service

定义业务层Bean的注解

(9)@Controller

定义控制器Bean的注解

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值