springboot简化了配置文件的配置,常用的spring、springmvc的配置文件已经在springboot中配置好了。使得开发更专注业务逻辑的实现,提高开发效率。
spring配置文件
public class Student {
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + ''' +
", sex='" + sex + ''' +
", age=" + age +
'}';
}
}
测试类:
public class TestXmlConfig {
@Test
public void test01(){
String config = "beans.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
// myStudent 是xml配置文件中配置的bean id属性值。
Student myStudent = (Student) ctx.getBean("myStudent");
System.out.println("获取的对象为: "+ myStudent);
}
}
javaConfig : 使用java类代替xml配置文件,是spring 提供的一种基于纯java类的配置方式。在这个配置类中@Bean创建java对象,并把对象注入到容器中。
需要使用2个注解:
创建配置类 MyConfig
import com.springboot.entity.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
/**
* @Bean: 注解
属性: name 相当于 bean标签中的id
注解没有标注name属性值的话,默认就是方法的名称 getStudent
*/
@Bean
public Student getStudent(){
Student student = new Student();
student.setAge(18);
student.setName("王五");
student.setSex("男");
return student;
}
}
测试类
import com.springboot.config.MyConfig;
import com.springboot.entity.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@Test
public void test02(){
ApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);
// @Bean 注解没有指出name属性值,默认是方法名称 getStudent
Student myStudent = (Student) ctx.getBean("getStudent");
System.out.println("获取的对象为: "+ myStudent);
}
参与评论
手机查看
返回顶部