spring注解驱动开发

1、传统的写配置文件的方式,配置一个类然后使用是用下面的方法:

使用:

2、使用注解的方式:

//告诉spring这是一个配置类
@Configuration
public class Anno {

    //给容器中注册一个bean,类型为返回值类型 id是默认方法名作为id
     @Bean
    public Person person(){
        return new Person("hdx",27);
    }
}

使用:

	public static void main(String[] args) {
		ApplicationContext context = new AnnotationConfigApplicationContext(Anno.class);
		Person bean = context.getBean(Person.class);
		System.out.println(bean.name); //输出结果 hdx
        //查看bean的名称
		String[] beanNamesForType = context.getBeanNamesForType(Person.class);
		for (String name : beanNamesForType) {
			System.out.println(name); //输出结果 person
		}
	}

此时如果我想改变bean的名称当然可以直接改,但是也可以在注解里面指定

 @Bean("person_alias")
    public Person person(){
        return new Person("hdx",27);
    }

3、关于包扫描

之前的做法是配置component-scan,这时候只要指定路径底下的文件配置了 @service @controller @Repository @component注解的都会被扫描到

用注解的做法:可以指定排除哪些包或者只包含哪些

4、@scope设置组件的作用域,单实例、多实例

首先确认下spring ioc容器里面的实例对象是否是单实例的——yes

         //spring IOC容器取出的对象都是单实例的
        ApplicationContext context = new AnnotationConfigApplicationContext(Anno.class);
        Object person = context.getBean("person_alias");
        Object persons = context.getBean("person_alias");
        System.out.println(person==persons); //true

添加scope注解可以控制bean的作用范围:

默认IOC容器启动都是创建单实例放到容器中,如果调成多实例

懒加载:

Conditional:按照一定的条件初始化bean

@import快速导入组件到IOC里

@Import(Color.class)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值