java-Spring 管理bean例子

Posted 与f

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java-Spring 管理bean例子相关的知识,希望对你有一定的参考价值。

Spring 通过2种方式管理bean

首先要导入Spring的包,(Spring.jar和commonslogging.jar) 或加载分开的...

在src目录下建立applicationContext.xml   (Spring 管理 bean的配置文件)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPEING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="user" class="com.cc8w.entiey.User"/>
</beans>

1.使用BeanFactory管理bean

2.使用ApplicationContext管理bean

package com.cc8w;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.cc8w.entiey.User;

public class TestBean {

    public static void main(String[] args) {
    
        //BeanFactory 管理bean
        Resource resource = new ClassPathResource("applicationContext.xml");
        BeanFactory factory =new XmlBeanFactory(resource);
        User user = (User) factory.getBean("user");
        System.out.println(user);
        
        //applicationContext 管理bean
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user1 = (User)context.getBean("user");
        System.out.println(user1);
        
    }

}

 

java的数据类型

package com.cc8w.entiey;

public class User {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
}

 

结果:

呃.. 写错了,应该时entity.

Spring 控制反转 依赖注入 (配置初始化参数-实例化参数)

1.接口注入

2.Setter注入(推荐)

3.构造器注入

 

以上是关于java-Spring 管理bean例子的主要内容,如果未能解决你的问题,请参考以下文章

JAVA-Spring框架之IOC(DI)

java-spring 错误 Unsupported class file major version 57

SpringBoot启动报错“Consider defining a bean of type ‘xxx.mapper.UserMapper‘ in your configuration.“(代码片段

spring练习,在Eclipse搭建的Spring开发环境中,使用set注入方式,实现对象的依赖关系,通过ClassPathXmlApplicationContext实体类获取Bean对象(代码片段

报错“Field pet in XXX.HelloController required a bean of type ‘XXX.Pet‘ that could not be found.“(代码片段

golang goroutine例子[golang并发代码片段]