Spring 注解编程IOC

本文详细介绍了Spring框架中的注解编程,包括Bean的注册、依赖注入、生命周期及资源属性赋值。重点讨论了@Component、@Service、@Controller、@Repository等注解,以及@Autowired、@Resource和@Inject的自动注入机制。还提到了循环依赖问题及其解决方案,并讲解了Bean的初始化和销毁方法。同时,文章探讨了@Configuration与其他注解的区别,以及如何处理配置文件属性乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Bean 注册

注册Bean的常用注解有@Component、@Service、@Controller、@Repository,通过扫描包的方式对这些注解进行解析注册Bean。

注解ApplicationContext:AnnotationConfigApplicationContext

常用注解

@Configuration
声明Bean Difinition的配置文件,相当于一个xml文件

@Bean
声明Bean的组件

@Configuration
public class CustomConfig {
    @Bean
    public Person person() {
        return new Person();
    }
}

相当于xml bean内容

<beans>
    <bean id="person" class="top.felixfly.entity.Person"/>
</beans>

bean的名称默认为方法名称,也可以通过@Bean(value=“person”)或者@Bean(“person”)进行指定

@ComponentScan
指定扫描路径

@Configuration
@ComponentScan("top.felixfly.spring.annotation")
public class ScanConfiguration {
}

相当于xml component-scan

<beans>
    <context:component-scan package="top.felixfly.spring.annotation"/>
</beans>

@ComponentScans
多个扫描路径,值为ComponentScan的数组,1.8以后可以用多个@ComponentScan代替此注解

@Scope
指定Bean的作用域,默认为singleton

  • singleton org.springframework.beans.factory.config.ConfigurableBeanFactory#SCOPE_SINGLETON
  • prototype org.springframework.beans.factory.config.ConfigurableBeanFactory#SCOPE_PROTOTYPE
  • request org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
  • session org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
@Configuration
public class CustomConfig {
    @Bean
    @Scope("singleton")
    public Person person() {
        return new Person();
    }
}

相当于xml中bean中scope属性

<beans>
    <bean id="person" class="top.felixfly.entity.Person" scope="singleton"/>
</beans>

@Lazy
懒加载,针对singleton Bean进行懒加载,默认情况下单实例Bean直接加载

@Configuration
public class CustomConfig {
    @Bean
    @Lazy
    public Person person() {
        return new Person();
    }
}

相当于xml中bean的lazy-init属性

<beans>
    <bean id="person" class="top.felixfly.entity.Person" lazy-init="true"/>
</beans>

@DependsOn

依赖关系注解

@Configuration
public class CustomConfig {

    @Bean
    @DependsOn("person")
    public Manager manager(){
        return new Manager();
    }

    @Bean
    public Person person(){
        return new Person();
    }
}

相当于xml中bean的depends-on属性

<beans>
    <bean id="manager" class="top.felixfly.entity.Manager" depends-on="person"/>
</beans>

@Order
Bean的排序,或者说是优先级,两个接口org.springframework.core.Ordered以及org.springframework.core.Priori

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值