springboot
springboot簡化了組態檔的配置,常用的spring、springmvc的組態檔已經在springboot中配置好了,使得開發更專注業務邏輯的實作,提高開發效率,
1.1基于xml的配置
spring組態檔
<?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="myStudent" >
<property name="name" value="https://www.cnblogs.com/rabbits-carrot/archive/2023/02/22/蔡劍波"/>
<property name="age" value="https://www.cnblogs.com/rabbits-carrot/archive/2023/02/22/20"/>
<property name="sex" value="https://www.cnblogs.com/rabbits-carrot/archive/2023/02/22/女"/>
</bean>
</beans>
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);
}
}
1.2 JavaConfig
? javaConfig : 使用java類代替xml組態檔,是spring 提供的一種基于純java類的配置方式,在這個配置類中@Bean創建java物件,并把物件注入到容器中,
需要使用2個注解:
- @Configuration: 這個注解作用在類上面,表示當前作用的類被當作組態檔使用,
- @Bean: 作用于方法上,表示宣告物件,把物件注入到容器中,
創建配置類 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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/544710.html
標籤:其他
下一篇:【牛客】2 基礎語法
