上文中Java Spring 注解(有xml配置文件)入门项目例子,我们讲解的是如何在有xml文件的帮助下,加入注解。而这篇文章是如何不使用配置文件添加注解的写法。
所谓不使用配置文件,其实是换了一种形式,不用xml文件,而是建了个java类来代替它。具体如下:
1.首先我们在com.ly.demo包下创建了ApplicationConfig.java类
package com.ly.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration//使用java类作配置文件时需要注解Configuration
//注:类名不可以命名为Configuration 否则会报错
public class ApplicationConfig{
//等价于<bean id="myPhone class="com.ly.demo.Phone"></bean>
@Bean(name="myPhone")
public Phone myPhone(){
return new Phone("mate9","Huawei","4000");
}
}
2.Phone类代码如下:
package com.ly.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("thePhone") //与<bean id="phone" class="com.ly.demo.Phone" ></bean> 等效
public class Phone {
@Value(value = "mate9")//与<property name="name" value="mate9" ></property>等效
private String name;
@Value(value = "Huawei")//与<property name="brand" value="Huawei" ></property>等效
private String brand;
@Value(value = "4000")//与<property name="price" value="4000" ></property>等效
private String price;
public Phone(){}
public Phone(String name, String brand, String price) {
super();
this.name = name;
this.brand = brand;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
3.测试类Test.java代码如下:
package com.ly.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig.class);//此处的方法与前文中使用的不同!
Phone phone = (Phone)ac.getBean("thePhone");
System.out.println(phone.getName());
}
}
4.结果应显示为图示结果即正确。
项目目录如下: