博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring——Spring使用注解开发
阅读量:3943 次
发布时间:2019-05-24

本文共 1901 字,大约阅读时间需要 6 分钟。

Spring——Spring使用注解开发

一、注解开发步骤

1.导包:

  • spring一系列包
    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()); }}

结果:

在这里插入图片描述

二、使用IOC注入(注解开发)

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/

你可能感兴趣的文章
path变量备份
查看>>
Lesson2.2 & 2.3 Maya command reference & quick help
查看>>
lesson 2.4 - Converting MEL Commands to Python
查看>>
Lesson3.2 variables
查看>>
3.4.2 - Operators & 3.4.3 division and truncation
查看>>
3.7.1 - Strings
查看>>
3.7.4 - Indexing and Slicing Strings
查看>>
3.7.5 - Modifying Strings
查看>>
3.7.6 - String Methods
查看>>
3.8 - Using the Print Function
查看>>
3.9.1 - Lists in Python
查看>>
3.9.2 - Lists - Adding and Removing Objects
查看>>
3.9.3 - Sorting Lists
查看>>
3.10 - Maya Commands: ls
查看>>
3.11 - Dictionaries in Python
查看>>
3.12 - Tuples in Python
查看>>
4.4 - For Loops
查看>>
4.2.2 - Logical and/or Operators
查看>>
Lesson 4 Part 2 Softmax Regression
查看>>
文章中运用到的数学公式
查看>>