package com.ant.spring;
public class HellWorld {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//构造器
public void hell() {
System.out.println("hell:"+this.name);
}
}
<?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">
<!-- 注入方式:
1.getter setters(常用)
2.构造器注入(死的应用)
3.接口注入(不常用,不推荐)
通过getters setters注入
配置spring
class:bean的全类名(包名+实体类类名),通过反射的方式在IOC容器中创建bean,并要求bean中必须有无参的构造器
id:标识容器中的bean.id 唯一
-->
<bean idpackage com.ant.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
//1.创建spring的IOC容器对象,并根据spring.xml文件实例化对象,调用property配置进行赋值
//ApplicationContext代表IOC容器
//ClassPathXmlApplicationContext:是ApplicationContext的实现类
ApplicationContext con=new ClassPathXmlApplicationContext("spring.xml");
//2.从IOC容器中获取bean并实例,利用id定位到IOC
HellWorld hellWorld=(HellWorld) con.getBean("hellworld");
hellWorld.hell();
}
}