注解就是将原来的xml配置的方式改用了@XXXX方式来代替
首先定义一个Ponse 实体类
package com.bean;
public class Ponse {
private String name;
private int age;
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
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 Ponse(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Ponse() {
super();
// TODO Auto-generated constructor stub
}
}
配置xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!--id:唯一的别名,class:包路径+类名 -->
<bean id="posnse" class="com.bean.Ponse">
<!--name:实体类中的name属性,value:给name赋的值 -->
<property name="name" value="jion"></property>
</bean>
</beans>
测试类
package com;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bean.Ponse;
import com.config.MianConfig;
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
Ponse ponse = (Ponse) applicationContext.getBean("posnse");
System.out.println(ponse.getName());
}
}
输出的结果:
注解版
先定义一个注解类 MianConfig
package com.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.bean.Ponse;
@Configuration //告诉spring这是一个配置类
public class MianConfig {
@Bean("ponse") //给容器注册一个bean,默认情况是用方法名来作为bean的id,可以在bean后指定id
public Ponse getPonse() {
// TODO Auto-generated method stub
return new Ponse("你好",12);
}
}
测试类
package com;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bean.Ponse;
import com.config.MianConfig;
public class Test {
public static void main(String[] args) {
//这里要注意一下//AnnotationConfigApplicationContext(MianConfig.class)这是一个注解类
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MianConfig.class);
Ponse ponse = (Ponse)applicationContext.getBean("ponse");
System.out.println(ponse.getName());
//获取bean的类型
String[] naStrings = applicationContext.getBeanNamesForType(Ponse.class);
for (String string : naStrings) {
System.out.println(string);
}
}
}
结果: