Spring框架复习06-spring注解开发快速入门 r囧r小猫 2022-02-04 02:25 189阅读 0赞 ## 第一步:引入jar包(这里是在前面的基础上添加的,就是多引入一个aop的jar包) ## ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4MTk4NDY3_size_16_color_FFFFFF_t_70][] ## 第二步:配置文件引入约束(context约束) ## 这个约束是注解开发所必须的 xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> </beans> ## 第三步:配置注解包扫描(扫描哪些包下的注解) ## <context:component-scan base-package="com.ctbu"/> ## 第四步:在类上和属性上写上注解 ## @Component("student") //相当于是配置文件中配置时 bean中的id属性 public class Student { private String name; private String age; private String sex; public String getName() { return name; } @Value("花木兰") //相当于是配置文件中配置的时候,属性的注入 public void setName(String name) { this.name = name; } public String getAge() { return age; } @Value("23") public void setAge(String age) { this.age = age; } public String getSex() { return sex; } @Value("女") public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", sex='" + sex + '\'' + '}'; } } ## 第五步:编写测试类 ## @Test public void test2(){ //加载配置文件 ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //获取配置的对象,通过配置文件中的id Student student = (Student) applicationContext.getBean("student"); System.out.println(student); } [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4MTk4NDY3_size_16_color_FFFFFF_t_70]: /images/20220204/09fa9e641b844ece948211b6ce192f1a.png
还没有评论,来说两句吧...