Spring AnnotationConfigApplicationContext配置

Spring AnnotationConfigApplicationContext

一.AnnotationConfigApplicationContext

Application大致分为三类:xmlApplicationContext,AnnotationConfigApplicationContext,WebApplicationContext。今天配置AnnotationConfigApplicationContext。
Annotation:注解,注解的作用是对类和方法的说明;
Config:配置;
ApplicationContext:应用程序上下文

PS:AnnotationConfigApplicationContext中的配置类相当于xml文件

二.配置Bean

1.新建配置类,添加@Configuration注解;
新建方法返回新建对象,并在方法上添加@Bean注解
配置类可添加@Autowired,@Inject,@Scope注解

import filmchart.entities.Film;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AnnotationConfig {
    @Bean
     public Films AnnotationConfig(){
         return new Films();
     }
}

配置@Configuration注解时的约束
1.配置类是non-final
2.配置类必须是非局部的
3.嵌套配置类声明为静态的

2.实体类

package filmchart.entities;

import org.springframework.stereotype.Component;

@Component
public class Films {
    private int fId;
    private String  name;
    private Double score;
   @Autowired 
    private Writer writer;

    public int getfId() {
        return fId;
    }
    public void setfId(int fId) {
        this.fId = fId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getScore() {
        return score;
    }

    public void setScore(Double score) {
        this.score = score;
    }

    public Writer getWriter() {
        return writer;
    }

    public void setWriter(Writer writer) {
        this.writer = writer;
    }
}

3.Test类

import filmchart.entities.Film;
import filmchart.entities.Films;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AnnotationTest {
    AnnotationConfigApplicationContext context;
    public AnnotationTest(){
        context = new AnnotationConfigApplicationContext();
        context.scan("filmchart");//通过指定包查询bean
        context.refresh();//刷新
    }
    @Test
    public  void film(){
     Films f1=   context.getBean(Films.class);
        Assert.assertNotNull(f1);
    }
    @Test
    public  void configBean(){
        Film f1=(Film) context.getBean("film1");
        Assert.assertEquals(1,f1.getId());

    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值