spring注入示例

本文通过一个具体的例子展示了如何使用Spring框架进行依赖注入。包括定义一个User类,并通过配置文件beans.xml设置其属性,最后在测试类中获取并打印这些属性。

实例类bean类:

package com.bjsxt.bean;

public class User {

 private int id;
 private String name;
 private String school;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getSchool() {
  return school;
 }

 public void setSchool(String school) {
  this.school = school;
 }

 public User() {

 }

 public static void meth() {
  System.out.println("这是spring的注入!");
 }
}

 

测试类:

package com.bjsxt.bean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestUser {

 public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext(
    new String[] { "beans.xml" });
  User u=(User) ctx.getBean("user");
  u.meth();
  System.out.println(u.getId());
  System.out.println(u.getName());
  System.out.println(u.getSchool());
 }
}

 

配置文件beans.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
         http://www.springframework.org/schema/context/spring-context.xsd">
        
         <bean id="user" class="com.bjsxt.bean.User">
          <property name="id" value="1"></property>
          <property name="name" value="张三"></property>
          <property name="school" value="清华大学"></property>
          
         </bean>
   <context:annotation-config/>
  
</beans>

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值