spring IOC

IOC

Inverse of COntrol,反转控制
相关依赖:spring-context

AOP

Aspect Oriented Programming,面向切面编程

@Configuration与@Bean的用法

告诉spring这是一个配置类,并将bean依赖注入
@ComponentScan: 告诉spring需要扫描的包
@Configuration // 告诉spring这是一个配置类
@ComponentScan(value = "com.atguigu",
        /* excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class})
        },*/
        includeFilters = {
            @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})
        },
        useDefaultFilters = false
)
public class MainConfig {
/*
*   <bean id="person" class="com.atguigu.bean.Person">
        <property name="age" value="18"></property>
        <property name="name" value="zhangsan"></property>

    </bean>
*
* */
    @Bean(value = "person02")
    public Person person() { // spring 默认会把方法名作为bean id,如果想改bean名称,可以Bean中加
        return new Person("lisi", 20);
    }
}
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
String[] beanNames = applicationContext.getBeanDefinitionNames(); # 获取所有的注解
String[] namesForType = applicationContext.getBeanNamesForType(Person.class); # 获取Person类型的注解的名称

@ComponentScan注解中过滤规则

001. 表示包扫描的时候需要过滤掉的
    type = FilterType.ANNOTATION表示根据注解类型过滤
 excludeFilters = {
    @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class})
}


002. 表示扫描时需要留下来的,
        type = FilterType.ASSIGNABLE_TYPE表示根据类名过滤
        type = FilterType.CUSTOM表示根据自定义类型过滤
    includeFilters = {
            @Filter(type = FilterType.ANNOTATION, classes = {Controller.class}),
            @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {BookService.class}),
            @Filter(type = FilterType.CUSTOM, classes = {MyTypeFilter.class})
    },

    useDefaultFilters = false, 表示不使用默认的过来规则,否则定义的Filter将不会起作用

)

@Scope调整作用域

spring中默认注入的依赖是单例模式
@Bean
public Person person() {
    System.out.println("给容器中添加Person......");
    return new Person("zhangsan", 25);
}

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
Person person01 = applicationContext.getBean("person", Person.class);
Person person02 = applicationContext.getBean("person", Person.class);
System.out.println(person01 == person02);//true spring中注入的依赖,默认都是单例的

懒加载:

由于单实例bean:默认再容器使用的时候创建对象;
懒加载:容器启动时不创建对象,第一次使用时才创建;
@Lazy

给容器中注册组件:

1. 包扫描+组件标注注解(@Controller/@Service/@Repository/@Component)
2. @Bean导入的第三方包里面的组件
3. @Import[快速给容器中导入一个组件]
    3.1 @Import(要导入到容器中的组件),容器中就会自动注册这个组件,id默认是全类名
    3.2 ImportSelector:返回需要导入的组件的全类名数组;
4. 使用Spring提供的FactoryBean
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值