Java Spring 注解(有xml配置文件)入门项目例子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/li99yangg/article/details/87364334

注解是一种在Java Spring编程(包括Mybatis等)下的一种编码方式,它的存在极大地降低了代码的重复性,但也由于他的简洁,导致对初学者入门有很大阻碍,这篇文章就是为了帮助初学者入门来讲解一下使用注解有哪些需要注意的地方。

1.首先,我们使用任何框架之前都需要导入相关的jar包,本次我们需要用到的有如下包(链接:https://pan.baidu.com/s/114tLmMGQR3KTfT0GL_mu_A

2.我们需要导入到项目中的lib文件夹中并Add to BuildPath(具体步骤可参照上一篇文章:Java Spring框架入门第一个小例子教程      https://pan.baidu.com/s/114tLmMGQR3KTfT0GL_mu_A

3.我们在src文件夹下创建一个config文件夹,(用于放置我们的xml文件),在该文件夹下右键->file,命名为application.xml文件(!!注意的是,必须在src下而不能创建在其他文件夹下,否则会因为找不到xml位置而报错)

-----------------------------------------------------------------------------------------------------------------------------------------------

此处是分割线,下面的步骤是常规不用注解的写法,看注解写法直接跳到下条分割线处,这两种写法是等效的。

4.我们在com.ly.demo包下建一个类,类名为Phone,我们为其补充属性以及getter/setter/构造方法

5.为我们的Application.xml配置文件补充内容(复制时别忘了修改箭头对应的属性)

<?xml version="1.0" encoding="UTF-8"?>       
<beans xmlns="http://www.springframework.org/schema/beans"       
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">      
 <bean id="thePhone" class="com.ly.demo.Phone" >      
  <property name="name" value="mate9"></property>
  <property name="brand"  value="Huawei"></property>
  <property name="price"  value="4000"></property>
 </bean>
</beans>

6.在com.ly.demo下创建测试类Test.java.并补充如下内容,运行之后会出现如下结果即成功。

package com.ly.demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
 public static void main(String[] args) {
  ApplicationContext ac = new ClassPathXmlApplicationContext("config/Application.xml");
  Phone phone = (Phone)ac.getBean("thePhone");
  System.out.println(phone.getName());
 }
}

------------------------------------------------------------------------------------------------

分割线  下面演示注解是如何运行的:

4.在Phone类前加入如下注解(其他内容一致)

5.xml文件修改为如下:

<?xml version="1.0" encoding="UTF-8"?>       
<beans xmlns="http://www.springframework.org/schema/beans"     
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
 xmlns:context="http://www.springframework.org/schema/context"    
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd    
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">   
 <context:component-scan base-package="com.ly.demo"></context:component-scan>
<!--  <bean id="thePhone" class="com.ly.demo.Phone" >       -->
<!--   <property name="name" value="mate9"></property> -->
<!--   <property name="brand"  value="Huawei"></property> -->
<!--   <property name="price"  value="4000"></property> -->
<!--  </bean> -->
</beans>

6.运行Test类,结果相同

以上就是JavaSpring下 有xml文件 注解的写法,有什么疑问欢迎在评论留言。

猜你喜欢

转载自blog.csdn.net/li99yangg/article/details/87364334