首先在maven中肯定要有spring的jar包
<!-- Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!-- Spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
第一步创建一个实现类
Kuang.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 这是一个实现类
*/
@Component //这个注解的意思是说明这个类被spring接管了 注册到spring容器中了
public class Kuang {
private String name;
private int age;
public String getName() {
return name;
}
@Value("HUAHUA")
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "kuang{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
第二 写一个java 充当xml文件
xml.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* 这个相当于配置文件Appliction.xml
*/
@Configuration //本质也是一个组件@Componet 代表这是一个配置类
//@ComponentScan("cn") 这个是指定要扫描的包 我这个实例都在一个包下面所以它没有也可以
public class xml {
@Bean
public Kuang get(){
return new Kuang();//返回要注入到bean的对象
}
}
测试类运行
test.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* 这是一个测试类
*/
public class test {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(xml.class);//这个地方反射的是充当xml文件的java类反射
Kuang bean = (Kuang)context.getBean("get");//这个get来自xml.java中配置了注解@Bean的那个方法
System.out.println(bean.getName());
}
}