Erlo

springboot01

2023-02-22 22:00:11 发布   63 浏览  
页面报错/反馈
收藏 点赞

springboot

springboot简化了配置文件的配置,常用的spring、springmvc的配置文件已经在springboot中配置好了。使得开发更专注业务逻辑的实现,提高开发效率。

1.1基于xml的配置

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);

    }
}
1.2 JavaConfig

​ javaConfig : 使用java类代替xml配置文件,是spring 提供的一种基于纯java类的配置方式。在这个配置类中@Bean创建java对象,并把对象注入到容器中。

需要使用2个注解:

  1. @Configuration: 这个注解作用在类上面,表示当前作用的类被当作配置文件使用。
  2. @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);

    }

登录查看全部

参与评论

评论留言

还没有评论留言,赶紧来抢楼吧~~

手机查看

返回顶部

给这篇文章打个标签吧~

棒极了 糟糕透顶 好文章 PHP JAVA JS 小程序 Python SEO MySql 确认