Spring

Spring下载和安装

包下载地址:https://repo.spring.io/ui/native/release/org/springframework/spring

内容:

src路径下创建xml文件

spring容器ApplicationContext(预初始化 lazy-init="true",资源访问Resource,事件机制,加载多个配置文件)

一、设值注入/构造注入(XML文件)/接口注入

<bean id="one" class="springClass.OneClass"/>

<!--  设值注入  通过set方法-->
<bean id="two" lazy-init="true" class="springClass.TwoClass">
    <!--  name指的是set中的类名  ref指的是bean中的id-->
    <property name="oneClass" ref="one"/>
</bean>

<!--  构造注入  通过构造函数-->
<bean id="three" class="springClass.ThreeClass">
    <constructor-arg ref="one" type="springClass.OneClass" index="0"/>
</bean>

通过spring容器调用对象

public static void main(String[] args) {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    OneClass o1 = (OneClass)applicationContext.getBean("one");
    OneClass o2 = applicationContext.getBean("one",OneClass.class);
}

接口注入用于获取Spring容器

二、资源访问(根据Resource加载资源)

<bean id="oneFile" class="springClass.OneClass">
    <!-- classpath类资源加载路径、file:///c:/文件-磁盘资源、http://www....网络资源-->
    <property name="resource" value="file:///C:/Users/LoveDonkey/Desktop/新建文本文档.txt"/>
    <property name="charset" value="utf-8"/>
</bean>
public class OneClass {
    private Resource resource;
    private String charset;
    public void setResource( Resource resource){ this.resource = resource;} //xml中绑定了资源路径
    public void setCharset( String charset){ this.charset = charset;} //xml中绑定了编码类型
    public void info() throws IOException { // 读取数据
        BufferedReader br = new BufferedReader( new InputStreamReader( resource.getInputStream(),charset));
        String line = null;
        while((line = br.readLine()) != null){
            System.out.println(line);
        }
    }
}

三、ApplicationContext事件机制 

applicationEvent、applicationListener

四、 Bean作用域 6种

<bean scope="xxxx">  

posted @ 2022-04-24 21:30  LoveDonkey  阅读(11)  评论(0编辑  收藏  举报