关于Spring注解配置的步骤

Posted 李俊----互联网技术传播者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于Spring注解配置的步骤相关的知识,希望对你有一定的参考价值。

今天分享一下 关于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注解配置的步骤的主要内容,如果未能解决你的问题,请参考以下文章

关于手写实现Spring注解实现自定义配置功能

关于手写实现Spring注解实现自定义配置功能

关于spring事务注解实战

关于Spring注解容器配置的那些事,掌握这几点,不再难!

关于Spring注解开发教程,打包全送你

关于spring@Resource注解的问题