spring中@Configuration的用法

背景

spring需要xml文件作为IOC容器,也就是spring的容器,用来管理对象。在spring4之后,JavaConfig(spring的一个子项目)成为了一个spring的核心功能。

@Configuration

@Configuration 等价于xml文件中的标签,用来管理生成,即在容器中交bean,获取出来后,就是对象。
在这里插入图片描述

使用

直接在类上使用@Configuration,说明这个类是配置类,即是IOC容器,用来创建bean,那么自然而然就会想到,@bean用来标记创建具体的bean,
在这里插入图片描述

项目目录

@Configuration
public class MyConfg {
    
    
    @Bean
    public Student getStudent(){
    
    
        return new Student();
    }
}

package com.yang.dao;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class Student {
    
    
    public String address;
    public  String[] books;
    public int age;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private Properties pro;

    public String getAddress() {
    
    
        return address;
    }

    public void setAddress(String address) {
    
    
        this.address = address;
    }

    public String[] getBooks() {
    
    
        return books;
    }

    public void setBooks(String[] books) {
    
    
        this.books = books;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public List<String> getHobbys() {
    
    
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
    
    
        this.hobbys = hobbys;
    }

    public Map<String, String> getCard() {
    
    
        return card;
    }

    public void setCard(Map<String, String> card) {
    
    
        this.card = card;
    }

    public Set<String> getGames() {
    
    
        return games;
    }

    public void setGames(Set<String> games) {
    
    
        this.games = games;
    }

    public Properties getPro() {
    
    
        return pro;
    }

    public void setPro(Properties pro) {
    
    
        this.pro = pro;
    }
}

测试类:


import com.yang.confg.MyConfg;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {
    
    
    public static void main(String[] args) {
    
    
        //获取上下文
       // ApplicationContext conteWxt = new ClassPathXmlApplicationContext("auto.xml");
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfg.class);
        Object getStudent = applicationContext.getBean("getStudent");
        System.out.println(getStudent.toString());
    }
}

易混点

下面4个注解用来把类注册到容器中,即xml文件中(还需要xml文件作为容器)
@Componet
@Controller
@Service
@Reposity
他们经常和<context:component-scans base-package=“org.yang.xxx”/>,//扫描包
或者//表明可以使用注解
一起用
在这里插入图片描述

在这里插入图片描述

但@Configuration不需要xml文件,直接本身就是容器,可以生产bean。往往和@Bean一起用
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_39463175/article/details/118716680
今日推荐