1. 程式人生 > >spring學習1:1.基於註解的bean

spring學習1:1.基於註解的bean

成了 返回值 ins location for onf 默認 san Coding

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
  <!-- 以前(很久)利用bean註冊組件(實體類) id方便在容器中獲取 -->
  <bean id="person" class="com.bean.Person">
  <property name="age" value="18"></property>
  <property name ="name" value="zhangsan"></property>
</bean>
</beans>

//以前配置文件的方式(bean.xml)-->被替換成了類(看上面)
@Configuration //告訴Spring這是一個配置類
public class Mainconfig {

//給容器註冊一個bean;類型為返回值類型,id默認為方法名
@Bean("person1")//指定id名
public Person person() {
  return new Person("王五", 10);
  }

}

/**/測試

public class MainTest {
public static void main(String[] args) {
  //以前通過加載配置文件去獲取
  /*ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
  Person bean = (Person) applicationContext.getBean("person");
  System.out.println(bean);*/
  /*out
  * Person [name=zhangsan, age=18]
  */
//基於註解的config
  AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Mainconfig.class);
  Person bean = applicationContext.getBean(Person.class);
  System.out.println(bean);
  /*out
  * Person [name=王五, age=10]
  */
  //獲取所有bean的id名
  String[] beanname = applicationContext.getBeanNamesForType(Person.class);
  for (String name : beanname) {
    System.out.println(name);
  }

  /*out

  person1

  */
  }

}

spring學習1:1.基於註解的bean