首先创建所需要的类:
package com.blushyes.vo; public class Student { private String name; private Integer age; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "Student{" + "name='" + name + ''' + ", age=" + age + ", sex='" + sex + ''' + '}'; } }
然后创建SpringConfig类用于配置容器:
package com.blushyes.config; import com.blushyes.vo.Student; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class SpringConfig { @Bean public Student createStudent(){ Student student = new Student(); student.setName("张三"); student.setAge(19); student.setSex("男"); return student; } }
@Configuration注解的意思是该类是用于配置容器的类。
@Bean可以指定id如@Bean(id=“myStudent”),默认为方法名。
从容器中提取对象:
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); //根据JavaConfig创建容器 Student student = (Student) context.getBean("createStudent"); //提取对象 System.out.println(student);
输出:
Student{name=‘张三’, age=19, sex=‘男’}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)