spring注解方式

  • 代码整体布局:
  • 代码如下:
    • pom.xml:
    • spring-1.xml:
    • Student:
    • Test:
    • Test2:
    • spring-2.xml:
    • Car:
    • Driver:
    • Test:
    • spring-3.xml:
    • IA:
    • ClsA1:
    • ClsA2:
    • MyCls:
    • MyCls2:
    • Dog:
    • Test:
    • Test2:
  • 讲解参考:

代码整体布局:


代码如下:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>mybatis_0822_KTLX</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.18</version></dependency></dependencies>
</project>

spring-1.xml:

<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><bean id="stu" class="com.test.Student" ><property name="name" value="张三"/><property name="sex" value="男"/><property name="age" value="20"/></bean>
</beans>

Student:

package com.test;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;//@Component:用于告诉spring,当前类的对象需要spring来管理。
//          里面的名字就相当于bean标签的id,作为对象的唯一标识
@Component("stu")
public class Student {private String name;private String sex;private Integer age;public Student() {System.out.println("=====Student 无参构造=====");}public Student(String name, String sex, Integer age) {this.name = name;this.sex = sex;this.age = age;}public String getName() {return name;}public void setName(String name) {System.out.println("========setName========:"+name);this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", sex='" + sex + '\'' +", age=" + age +'}';}
}

Test:

package com.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import javax.annotation.Resource;public class Test {@Resourceprivate Student stu;public static void main(String[] args) {//创建spring容器ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-1.xml"); //运行结果:=====Student 无参构造===== ========setName========:张三}}

Test2:

package com.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test2 {public static void main(String[] args) {//通过注解从spring容器中获取对象//1.在spring配置文件中,配置包扫描//2.在需要被spring管理的类上加特定注解ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-1.xml");Student stu=ctx.getBean(Student.class);System.out.println(stu); //运行结果:=====Student 无参构造===== ========setName========:张三  Student{name='张三', sex='男', age=20}Student stu1=(Student)ctx.getBean("stu");System.out.println(stu1); //运行结果: Student{name='张三', sex='男', age=20}}
}

spring-2.xml:

<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="com.test2"/>
</beans>

Car:

package com.test2;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;@Component("mycar") //通过注释,可以用在任意对象上
//@Service  //本质就是@Component这个注释的别名,用于Service层的对象
//@Repository //本质就是@Component这个注释的别名,用于数据访问层的对象
public class Car {//品牌@Value("宝马")private String brand;//价格@Value("2000")private int price;//时速@Value("120")private int space;public Car() {}public Car(String brand, int price, int space) {this.brand = brand;this.price = price;this.space = space;}public void run(){System.out.println(this.brand+"在跑");}public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}public int getPrice() {return price;}public void setPrice(int price) {this.price = price;}public int getSpace() {return space;}public void setSpace(int space) {this.space = space;}@Overridepublic String toString() {return "Car{" +"brand='" + brand + '\'' +", price=" + price +", space=" + space +'}';}
}

Driver:

package com.test2;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import javax.annotation.Resource;@Component  //当注释没有指定id名字的时候,spring自动用类名小驼峰做对象的id名
public class Driver {//@Value只用于注入普通值@Value("张三")private String name;@Value("20")private Integer age;//@Autowired 用于注入对象类型的值(按照类型注入对象,前提是spring容器中有该类型的对象)//           该注释属于spring框架下的注释。特征是按照类型注入对象//@Autowired@Resourceprivate Car car;public Driver() {}public Driver(String name, Integer age, Car car) {this.name = name;this.age = age;this.car = car;}//开车public void drive(){System.out.println(this.name+"开车");this.car.run();}public String getName() {return name;}public void setName(String name) {//注解方式没有调用setter方法System.out.println("==========setName==============:"+name);this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Car getCar() {return car;}public void setCar(Car car) {this.car = car;}@Overridepublic String toString() {return "Driver{" +"name='" + name + '\'' +", age=" + age +", car=" + car +'}';}
}

Test:

package com.test2;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {public static void main(String[] args) {ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-2.xml");//获取容器中的司机对象Driver driver=ctx.getBean(Driver.class);//调用开车的方法driver.drive(); //运行结果:张三开车 宝马在跑Car car=ctx.getBean(Car.class);System.out.println(car);   //运行结果:Car{brand='宝马', price=2000, space=120}Car mycar=(Car)ctx.getBean("mycar");System.out.println(mycar); //运行结果:Car{brand='宝马', price=2000, space=120}}}

spring-3.xml:

<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="com.test3"/>
</beans>

IA:

package com.test3;public interface IA {void test();
}

ClsA1:

package com.test3;import org.springframework.stereotype.Component;@Component
public class ClsA1 implements IA{@Overridepublic void test() {System.out.println("这是A1测试");}
}

ClsA2:

package com.test3;import org.springframework.stereotype.Component;@Component
public class ClsA2 implements IA{@Overridepublic void test() {System.out.println("这是A2测试");}
}

MyCls:

package com.test3;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;import javax.annotation.Resource;@Component //当注释没有指定id名字的时候,spring自动用类名小驼峰做对象的id名
public class MyCls {
//    @Autowired
//    private IA a;  //运行结果:ERROR:expected single matching bean but found 2: clsA1,clsA2//    //@Autowired先按类型,再按照名字注入
//    @Autowired
//    private IA clsA1;    //指定名字注入。 ClsA1类名小写clsA1 。
//
//    public void show(){
//        this.clsA1.test();
//    }                   //运行结果:这是A1测试//@Autowired先按类型,再按照名字注入@Autowired@Qualifier("clsA1") //按名字注入对象aprivate IA a;public void show(){this.a.test();}                   //运行结果:这是A1测试}

MyCls2:

package com.test3;import org.springframework.stereotype.Component;import javax.annotation.Resource;@Component
public class MyCls2 {//    @Resource(name = "clsA1")
//    private IA a;
//
//    public void show(){
//        this.a.test();
//    }                   //运行结果:这是A1测试//    @Resource
//    private IA clsA1; //指定名字注入
//
//    public void show(){
//        this.clsA1.test();
//    }                   //运行结果:这是A1测试//    //先按名字,再按类型注入
//    @Resource
//    private IA a;
//
//    public void show(){
//        this.a.test();
//    }  //运行结果:BeanNotOfRequiredTypeException: Bean named 'a' is expected to be of type 'com.test3.IA' but was actually of type 'com.test3.Dog'//先按名字,再按类型注入@Resourceprivate IA a;public void show(){this.a.test();} //运行结果:NoUniqueBeanDefinitionException: No qualifying bean of type 'com.test3.IA' available: expected single matching bean but found 2: clsA1,clsA2
}

Dog:

package com.test3;import org.springframework.stereotype.Component;//@Component("a")
@Component("dog")
public class Dog {}

Test:

package com.test3;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {public static void main(String[] args) {ApplicationContext ac=new ClassPathXmlApplicationContext("spring-3.xml");MyCls myCls=ac.getBean(MyCls.class);
//        ac.getBean(MyCls.class);myCls.show();}
}

Test2:

package com.test3;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test2 {public static void main(String[] args) {ApplicationContext ac=new ClassPathXmlApplicationContext("spring-3.xml");MyCls2 myCls2=ac.getBean(MyCls2.class);myCls2.show();}}

讲解参考:






// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';

spring注解方式 2022/08/22相关推荐

  1. (转)使用Spring注解方式管理事务与传播行为详解

    http://blog.csdn.net/yerenyuan_pku/article/details/52885041 使用Spring注解方式管理事务 前面讲解了怎么使用@Transactional ...

  2. 【Spring系列】 Spring注解方式实现IOC、DI及其Spring其他注解

    文章目录 注解回顾 JDK内置注解 自定义注解 1.声明一个注解类,由`@interface`修饰 2.通过元注解修饰注解的定义 `@Target`:(常用) `@Retention`:(常用) `@ ...

  3. ActiveMQ学习总结(10)——ActiveMQ采用Spring注解方式发送和监听

    对于ActiveMQ消息的发送,原声的api操作繁琐,而且如果不进行二次封装,打开关闭会话以及各种创建操作也是够够的了.那么,Spring提供了一个很方便的去收发消息的框架,spring jms.整合 ...

  4. Spring 注解方式实现 事务管理

    2019独角兽企业重金招聘Python工程师标准>>> 使用步骤: 步骤一.在spring配置文件中引入<tx:>命名空间 <beans xmlns="h ...

  5. spring 注解方式 事务管理

    使用步骤: 步骤一.在spring配置文件中引入<tx:>命名空间 <beans xmlns="http://www.springframework.org/schema/ ...

  6. spring注解方式注入bean

    用注解的方式注入bean,spring的配置文件也要增加一些约束和导入注解所在的包 applicationContext.xml 1 <?xml version="1.0" ...

  7. spring注解方式整合Dubbo源码解析

    系列文章目录 前言 本节我们的Dubbo源码版本基于2.6.x 在前一章我们的整合案例中,我们有几个比较关键的步骤: 在启动类上标注了@EnableDubbo注解 在provider类上面标注了@Se ...

  8. Spring注解方式实现定时器

    一.springmvc.xml中添加以下配置 1.beans添加xmlnx:task xmlns:task="http://www.springframework.org/schema/ta ...

  9. spring 注解方式配置Bean

    概要: 再classpath中扫描组件 组件扫描(component scanning):Spring可以从classpath下自己主动扫描.侦測和实例化具有特定注解的组件 特定组件包含: @Comp ...

最新文章

  1. C++函数指针解引用
  2. JZOJ 5629. 【NOI2018模拟4.4】Map
  3. 战双帕弥什显示服务器满员,战双帕弥什星火和信标服务器有何区别
  4. web服务器检测工具
  5. pyspark分类算法之逻辑回归模型实践【binomialLogisticRegression+multinomialLogisticRegression】
  6. NYOJ a problem is easy
  7. 大数据之Hadoop图解概述
  8. 基于树莓派的语音机器人
  9. 组合数学—什么是组合数学(1)
  10. 洛谷 P1653 猴子 解题报告
  11. matlab输入二项分布函数,MATLAB如何使用binornd函数生成二项分布随机数
  12. 操作系统MSXML组件版本过低,导致启动失败的原因
  13. ubuntu_pip-install_WARRING:XXX is not on PATH ...
  14. 参考文献起止页码怎么写_怎么看论文的起止页码
  15. POX控制器的分析(二)
  16. 个人日记-学习究竟是什么读后感3-2020/7/13
  17. [Android 硬件] Eclipse错误:Conversion to Dalvik format failed with error 1
  18. 【Jee---监听器】
  19. 科大讯飞语音引擎_科大讯飞发布智能录音笔SR502
  20. 使用excel画数据曲线

热门文章

  1. matlab三维立体空间图,三维空间作图.ppt
  2. 中国股市中的庄散之间的较量!
  3. poj 1305 Fermat vs. Pythagoras(毕达哥斯拉三元组)
  4. 幸运抽奖小程序-java基础知识
  5. mongo的安装及数据库认证的使用
  6. Javascript漂浮气球
  7. 计算机系统要素-从零开始构建现代计算机--第一章,01-用与非门实现与戓非
  8. CRC-16 Modbus代码
  9. 成功的UI是无形的-A GREAT UI IS INVISIBLE
  10. DOM元素的特性和属性