码迷,mamicode.com
首页 > 编程语言 > 详细

关于Spring注解配置的步骤

时间:2019-02-22 00:48:39      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:col   ring   rop   etag   流程   xmlns   war   ret   location   

今天分享一下 关于Spring注解配置的流程

1 导包:如下图所示技术图片

2 书写User和Car类  代码如下

package cn.lijun.bean;

public class Car {
private String name;
private String color;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}


public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Car [name=" + name + ", color=" + color + "]";
}

}

package cn.lijun.bean;

import org.springframework.stereotype.Component;

@Component("user")
public class User {
private String name;
private Integer age;
private Car car;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", car=" + car + "]";
}

}

3 书写配置文件 并且导入约束  代码如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd ">
<context:component-scan base-package="cn.lijun.bean"></context:component-scan>
</beans>

4 书写测试文件demo  代码如下

package cn.lijun.demo1;


import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.lijun.bean.User;

public class demo {
public static void main(String[] args) {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("appliactionContext.xml");
User u1 = (User)ac.getBean("user");
System.out.println(u1);
}


}

5 给User 配置@Component("user")并且给值为

@Value("lijun")
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
@Value("22")

6 测试结果如下

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
User [name=lijun, age=22, car=null]

关于Spring注解配置的步骤

标签:col   ring   rop   etag   流程   xmlns   war   ret   location   

原文地址:https://www.cnblogs.com/lijun6/p/10415951.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!