spring中通常使用@Configuration和@Bean,@Value等纯注解的形式来简化xml的bean配置,这和springboot项目开发的理念很相似,尽量不用spring的xml来配置bean,下面开始学习这几个注解的使用方法。
1:在pom.xml文件中加入Spring maven jar包,如果是spring4.0以上的版本,则不用添加cglib动态代理jar包,如下。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tpyyes</groupId> <artifactId>springDemo</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.11.RELEASE</version> </dependency> <!-- spring4.0版本以上不需要添加cglib maven库--> <!--<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.5</version> </dependency> --> </dependencies> </project>
2:创建一个简单的HelloWorld接口类,如下。
package com.tpyyes;
public interface HelloWorld {
void printHelloWorld(String msg);
}3:创建HelloWorldImpl类,并实现HelloWorld接口,添加一个属性content,并使用@Value注解给content属性赋值,如下。
package com.tpyyes;
import org.springframework.beans.factory.annotation.Value;
public class HelloWorldImpl implements HelloWorld{
@Value(",我爱你")
private String content;
public void printHelloWorld(String msg) {
System.out.println("Hello : " + msg+content);
}
}4:自定义Appconfig类,使用@Configuration注解告诉spring这是一个spring bean配置,然后使用@Bean注解给这个bean命名,如下。
package com.tpyyes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean(name="helloBean")
public HelloWorld helloWorld() {
return new HelloWorldImpl();
}
}5:在main方法中使用AnnotationConfigApplicationContext注解配置类来加载Appconfig配置,并调用HelloWorldImpl类里面的方法,如下。
package com.tpyyes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyApp {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
HelloWorld obj = (HelloWorld)context.getBean("helloBean");
obj.printHelloWorld("张三");
}
}右键运行main方法,输出结果如图所示。
