spring实战学习笔记(一)spring装配bean
最近在学习spring boot 发现对某些注解不是很深入的了解。看技术书给出的实例 会很疑惑为什么要用这个注解? 这个注解的作用?有其他相同作用的注解吗?这个注解的运行机制是什么?等等 springboot 相对spring 改变了些规则和使用方式。总感觉 还是需要把springboot的祖先了解下。
买了本spring 实战4 希望对我的了解有帮助。
spring 的出现代替了更加重量级的企业java技术, 相对EJB 它提供了 简单的编程和轻量级。
一 spring bean java配置
环境:java version "1.8.0_181" tomcat 8.0
spring 框架jar包下载 http://repo.spring.io/release/org/springframework/spring/
在eclipse 新建项目导入spring基础jar
创建实体类:
1 package soundsystem; 2 3 import org.springframework.context.annotation.ComponentScan; 4 import org.springframework.context.annotation.Configuration; 5 import org.junit.Test; 6 @Configuration 7 @ComponentScan(basePackages= {"com.lzl.spring.test","soundsystem"}) 8 public class CDPlayerConfig { 9 }
import soundsystem.SgtPeppers;
public class TestCD {
public void play() {
SgtPeppers bean = (SgtPeppers) applicationContext2.getBean("sgtPeppers");
if(bean!= null) {
bean.play();
}else {
System.out.println("beanis null");
}
}
但是一直报错:No tests found matching [{ExactMatcher:fDisplayName=play], {ExactMatcher:fDisplayName=play(com.lzl.spring.test.TestCD)], {LeadingIdentifierMatcher:fClassName=com.lzl.spring.test.TestCD,fLeadingIdentifier=play]] from org.junit.internal.requests.ClassReques
也没有详细的报错信息 ,之后把测试内容放在了main方法里面
1 package com.lzl.spring.test; 2 3 4 import org.springframework.context.annotation.AnnotationConfigApplicationContext; 5 6 import soundsystem.CDPlayerConfig; 7 import soundsystem.SgtPeppers; 8 public class TestCD { 9 10 11 public static void main(String[] args) { 12 AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(CDPlayerConfig.class); 13 SgtPeppers bean = (SgtPeppers) applicationContext2.getBean("sgtPeppers"); 14 15 if(bean != null) { 16 bean .play(); 17 }else { 18 System.out.println("bean is null"); 19 } 20 21 22 } 23
运行结果抛
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.springframework.context.support.AbstractApplicationContext.<init>(AbstractApplicationContext.java:153)
at org.springframework.context.support.GenericApplicationContext.<init>(GenericApplicationContext.java:100)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:60)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:82)
at com.lzl.spring.test.TestCD.main(TestCD.java:13)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more
最后下载了 apache-common-logging :http://commons.apache.org/proper/commons-logging/download_logging.cgi 放入项目lib包下构建了 运行成功