HelloSpring
第一个Spring代码
1.新建实体类
@Data @NoArgsConstructor @AllArgsConstructor public class Hello { private String name; private int age; public void show(){ System.out.println("hello" + " "+name); } }
2.xml配置文件
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core
使用Spring来生成对象,在Spring中这些都称为Bean
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
原来创建对象
类型 变量名 new 类型();
Hello hello = new Hello();
id hello 对应原来的变量名,也可以看做是对象名字
class com.chen.pojo.Hello 全局类型
property 给对象中的某个属性复制 name 就确定了某个属性
value 给属性复制的值
-->
<bean class="com.chen.pojo.Hello" id="hello">
<property name="name" value="Spring"/>
</bean>
<bean class="com.chen.pojo.Hello" id="hello1">
<property name="name" value="Spring"/>
<property name="age" value="10"/> //age是int型
</bean>
</beans>
3.实例化一个容器
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml"); //可以有多个配置文件
4.实现hello Spring
import com.chen.pojo.Hello; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Mytest { public static void main(String[] args) { //实例化一个容器 //参数可以有多个配置文件,用逗号分开就好了 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //使用Spring来创建对象,就是从容器中获取 Hello hello = (Hello) context.getBean("hello");//配置文件bean的id就是生成的对象的名字 hello.show();
Hello hello1 = (Hello) context.getBean("hello1"); //age是int型,在配置文件中value也是"10"
System.out.println(hello1.toString());
}
}

hello对象是由Spring创建的。我们再也不用new对象了!
在配置文件中property就是依靠set注入的。如果将代码中的set注释掉的话,直接配置文件报错!

在传递参数时候,value是基本类型
ref是配置文件中已经创建好的bean的id

5. 当一个实体类中没有无参构造方法时候
使用Spring时候,当配置文件被加载时候,就用无参的构造方法生成对象!生成的对象放在容器中。所以当存在没有无参构造器的类的时候生成对象时候就发生变化了



有参构造还可以通过下标去实现注入,下标从0开始!


浙公网安备 33010602011771号