本文共 1901 字,大约阅读时间需要 6 分钟。
1.导包:
org.springframework spring-webmvc 4.3.9.RELEASE
2.配置Spring的配置文件
需要在配置文件中添加一个约束context:3.配置自动扫描注解组件
4.编写代码,注解标识
package com.muhan.demo;import org.springframework.stereotype.Component;/* 四个注解(作用一样,都是为了spring的自动扫描能找到这个类,参数为对象的名称): @Component : 组件 bean @Controller :web层 @Service : service层 @Repository :dao层 等价于:*/@Component("user")public class User { private String name="穆学习"; public String getName() { return name; }}
5.测试
import com.muhan.demo.User;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestAnn { @Test public void test(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); User user = (User) context.getBean("user"); System.out.println(user.getName()); }}
结果:
1.可以不提供set方法,直接在属性名上添加一个@Value()
package com.muhan.demo;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Controller;//@Controller注解是为了spring自动扫描能够扫描到,参数为对象名@Controller("user2")public class User2 { /* 相当于:*/ @Value("穆学习2号") private String name; public String getName() { return name; }}
2.测试:
import com.muhan.demo.User2;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestAnn2 { @Test public void test(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); User2 user = (User2) context.getBean("user2"); System.out.println(user.getName()); }}
结果:
转载地址:http://goiwi.baihongyu.com/