什么网站可以做excel表格,城乡建设行业证书查询,广州网页制作培训,深圳东门希尔顿欢朋酒店文章目录 创建 Spring 项目创建一个普通的 Maven 项目添加 Spring 依赖IDEA更换国内源 运行第一个 Spring 项目新建启动类存储 Bean 对象将Bean注册到Spring 获取并使用 Bean 对象 创建 Spring 项目
创建一个普通的 Maven 项目
首先创建一个普通的 Maven 项目 添加 Spring 依… 文章目录 创建 Spring 项目创建一个普通的 Maven 项目添加 Spring 依赖IDEA更换国内源 运行第一个 Spring 项目新建启动类存储 Bean 对象将Bean注册到Spring 获取并使用 Bean 对象 创建 Spring 项目
创建一个普通的 Maven 项目
首先创建一个普通的 Maven 项目 添加 Spring 依赖
在项⽬的 pom.xml 中添加 Spring 框架的⽀持 dependenciesdependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion5.2.3.RELEASE/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-beans/artifactIdversion5.2.3.RELEASE/version/dependency
/dependencies注意在xml 文件里添加代码后只是声明了而已项目并没有加载需要点击 刷新加载依赖。 这个重新加载依赖默认是从国外的官网去下载的因此速度会很慢。 需要更换IDEA 的源为国内源 IDEA更换国内源
第一步打开IDEA的设置里找到 Maven 的设置选项栏 第二步查看 “User settings file”该栏上的路径里是否存在 “settings.xml”文件如果没有手动创建 settings.xml 文件并添加以下代码
?xml version1.0 encodingUTF-8?
settings xmlnshttp://maven.apache.org/SETTINGS/1.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsdpluginGroups/pluginGroupsproxies/proxiesservers/serversmirrorsmirroridalimaven/idnamealiyun maven/nameurlhttp://maven.aliyun.com/nexus/content/groups/public//urlmirrorOfcentral/mirrorOf /mirror/mirrorsprofiles/profiles
/settings第三步添加完 settings.xml 文件后将该路径下的 repository 文件夹下的所有文件都删掉之后重新下载加载依赖 等待完成即可
运行第一个 Spring 项目
新建启动类
上述说明已经是成功的创建了一个 Spring 项目了接下来就将项目运行起来。
首先需要在 src下的main下的java里新建一个启动类这个启动类里包含了main方法 Spring 项目的运行都是从这个main方法开始的
存储 Bean 对象
对于 Spring 而言每一个存到里面的对象都称为 Bean 对象。也就是说我们需要用到什么类都得先写好类之后存到 Spring 中
例如 现在新建了一个学生类 将Bean注册到Spring
那么有了 Bean 之后就得将 Bean 注册到 Spring 中。这就的借助一个 xml文件。
在 src中的main中的resources中新建一个 xml 文件并写入如下代码 ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contenthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd
/beans上述的代码和操作是固定不变的然后在 beans 中加入我们需要注册的 Bean操作如下 bean idstudent classspring.demo.Student/bean在bean里面的 id属性就是注册到Spring中该Bean的标识可任取但是获取Bean的时候需要用到因此推荐合理合规的取名在bean里面的class属性是注册的这个Bean所在的路径从java这个包下的子包开始算起 获取并使用 Bean 对象
上述已经将 Bean 注册到 Spring 中了那么接下来就开始从 Spring 中获取到 Bean 对象去进行使用
首先这个 Bean 已经是在 Spring 中了所以需要先获取到 Spring 的上下文对象然后从该对象中获取到 Bean 对象。以下操作均在启动类中进行 获取Bean对象的方法有很多种本文章不深究方法仅介绍 Spring 项目的运行 // 获取 Spring 的上下文对象
ApplicationContext context new ClassPathXmlApplicationContext(spring-config.xml);这里需要特别注意传的参数必须与刚刚所建的xml文件名一致并且需要带上 .xml 后缀名
// 获取 Bean 对象
Student student (Student) context.getBean(student);注意需要获取哪个 Bean 对象就需要传入在注册 Bean使所设置的id属性的值
// 使用 Bean 对象
student.print(hello world);获取到Bean 对象后就可以正常使用对象了
运行项目即可 可以看到 Student类的构造函数也被执行了说明将Student类存入到Spring时Spring存的就是Student类的实例