springboot中注解详解(springboot01)
导读:springboot springboot简化了配置文件的配置,常用的spring、springmvc的配置文件已经在springboot中配置好了。使得开发更专注业务逻辑的实现,提高开发效率。...
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" class="com.springboot.entity.Student"> <property name="name" value="蔡剑波"/> <property name="age" value="20"/> <property name="sex" value="女"/> </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); }创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!