首页 > 编程语言 > 详细

spring使用注解的方式创建bean

时间:2019-11-15 17:33:04      阅读:151      评论:0      收藏:0      [点我收藏+]

 1、创建一个bean

package com.springbean;

public class Person {

    private  String name;
    private Integer age ;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

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

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

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

2、创建配置类:

import com.springbean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PersonConfig {

    @Bean
  //@Bean("myperson") 这是设置bean的名字 public Person person(){ return new Person("张三",20); } }

 


3、测试
import com.spring.config.PersonConfig;
import com.springbean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ApplicationTest {
    public static void main(String[] args) {
        
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);

    //获取bean的类型,默认是方法名,需要修改就在配置类中@Bean里面加上名字
    String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
    for (String beanType : beanNamesForType){
    System.out.println(beanType);
    }
  } 
}
 
打完收工
 
2
 

spring使用注解的方式创建bean

原文:https://www.cnblogs.com/tdyang/p/11867704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!