Spring 框架部分注解

SpringBenFactory类

package cn.tedu.spring;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;

import java.util.Random;

@Configurable
public class SpringBeanFactory {

    @Bean
    public Random random(){
        return new Random();
    }
}

SpringRunner类

package cn.tedu.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Random;

public class SpringRunner {
    public static void main(String[] args) {
        //1.加载spring (可以敲大写ACAC筛选出来)
        AnnotationConfigApplicationContext ac
                =new AnnotationConfigApplicationContext(SpringBeanFactory.class);
        //2.从spring中获取对象   getBean跟SpringBeanFactory类的@Bean注解对应
        Random random= (Random) ac.getBean("random");
        //3.测试使用对象
        System.out.println("random>"+random);
        System.out.println("random>"+random.nextInt(100));
        //4.关闭
        ac.close();
    }
}

@Bean :SpringBenFactory类中必须添加@Bean注解,作用是Spring框架自动调用此方法,并管理此方法返回的结果.

@Configurable:在此代码中此注解可以不添加。

- `@Component`:通用组件注解
  - `@Controller`:应该添加在“控制器类”上
  - `@Service`:应该添加在“业务类”上
  - `@Repository`:应该添加在“数据存取类”上
- 另外,`@Configuration`是一种特殊的组件,应该添加在“配置类”上,当执行组件扫描时,添加了`@Configuration`注解的类也会被创建对象

其它:

- 可以在`@Component`等组件注解(不包含`@Configuration`)中配置字符串参数,以显式的指定Bean的名称

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雷雄雄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值