1.springboot = spring + springmvc
2.常用框架配置好了
3.开发效率高
是spring提供的Java类配置容器,配置springIOC容器的纯Java方法。
两个注解 1.@Configuration放在类的上面,表示这个类作为配置文件使用
2.@Bean声明对象,把这个对象注入到容器之中。
案例:创建student类:
package com.gizzard.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 + ''' +
'}';
}
}
使用beans.xml方法:
在resources里面创建beans.xml
测试:
@Test
public void test01(){
String config="beans.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
Student student = (Student) ctx.getBean("myStudent");
System.out.println(student);
}
使用JavaConfig方式:
创建SpringConfig类
package com.gizzard.config;
import com.gizzard.vo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig {
@Bean
public Student createStudent() {
Student s1 = new Student ();
s1.setName("张三");
s1.setAge(22);
s1.setSex("男");
return s1;
}
@Bean(name = "lisiStudent")
public Student makeStudent() {
Student s1 = new Student ();
s1.setName("lisi");
s1.setAge(22);
s1.setSex("男");
return s1;
}
}
测试:
@Test
public void test02(){
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
Student student = (Student) ctx.getBean("createStudent");
System.out.println(student);
}
@Test
public void test03(){
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
Student student = (Student) ctx.getBean("lisiStudent");
System.out.println(student);
}
@ImporResource
@ImporResource
在当作为配置文件的类中加入该注解可以将配置文件中的bean也加入到该类之中。
@Configuration
@importResource(value = "classpath:applicationContext.xml")
public class SpringConfig {
@Bean
public Student createStudent() {
Student s1 = new Student ();
s1.setName("张三");
s1.setAge(22);
s1.setSex("男");
return s1;
}
@Bean(name = "lisiStudent")
public Student makeStudent() {
Student s1 = new Student ();
s1.setName("lisi");
s1.setAge(22);
s1.setSex("男");
return s1;
}
}



