spring组件注册 @Configuration @Bean

@Configuration 表示此类是一个配置类,和用xml表示的配置文件相同

@Bean表示注册一个组件,注册的bean的类型为方法返回值的类型

package com.zyc.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;

import com.zyc.spring.bean.Person;

//配置类
@Configuration
public class MainConfig {
	@Bean("person1")
	public Person person(){
		return new Person("li",9);
	}

}

对应测试类

package com.zyc.spring.cases;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.zyc.spring.bean.Person;
import com.zyc.spring.config.MainConfig;

public class MainCase {
	
	public static void main(String[] args) {
//		ApplicationContext application = new ClassPathXmlApplicationContext("beans.xml");
//		Object bean = application.getBean("person");
//		System.out.println(bean);
		
		ApplicationContext an = new AnnotationConfigApplicationContext(MainConfig.class);
		Person bean = an.getBean(Person.class);
		String[] names = an.getBeanNamesForType(Person.class);
		for(String str :names){
			System.out.println(str+"===");
		}
	}

}

pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.zyc.spring</groupId>
  <artifactId>springL</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springL</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.3.RELEASE</version>
</dependency>
  </dependencies>
</project>

pojo

package com.zyc.spring.bean;

public class Person {
	
	private String name;
    private int age;
    
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	public Person(String name,int age){
		name = this.name;
		age = this.age;
	}
	
	public Person(){
		
	}
	
	public String toString() {
		return "Person [name=" + name + ", age=" + age +  "]";
	}
	

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值